Another question from total Python newbie.
I have an array, user can input 5 different words/sentences, after user enters those 5, user enters one of the 5 texts again and program removes this string from array, than user adds another string and it appends directly to the Index = 0.
But the problem begins when i want to run over this array and find if any of the strings in the array have at least 2 words.
Text = []
for i in range(0, 5):
Text.append(input('Enter the text: '))
print (Text)
for i in range(0, 1):
Text.remove(input('Enter one of the texts you entered before: '))
print (Text)
for i in range(0, 1):
Text.insert(0,input('Enter Some Text: '))
print (Text)
for s in Text:
if s.isspace():
print(Text[s])
Output :
Enter the text: A ['A'] Enter the text: B ['A', 'B'] Enter the text: CD ['A', 'B', 'C D'] Enter the text: E ['A', 'B', 'C D', 'E'] Enter the text: F ['A', 'B', 'C D', 'E', 'F'] Enter one of the texts you entered before: F ['A', 'B', 'C D', 'E'] Enter Some Text: G ['G', 'A', 'B', 'C D', 'E'] Press any key to continue . . .
So, my code doesn't do anything, i need to somehow find if any of the strings have at least 2 words and print all of those words.
for s in Text:
if s.isspace():
print(Text[s])
In the code above, s is the full string for example in your example s could be 'CD' and this string is not a space.
To check if s has two or more words you can use .split(' ') but before that you have to .strip() your string to delete spaces from borders.
s = 'Hello World '
print(s.strip().split(' '))
>>> ['Hello', 'World']
In the example above, s has two spaces, so strip delete the last space because is a border space and then split gives you a list of string that are separate by spaces.
So the solution to your problem could be
for s in Text:
if len(s.strip().split(' ')) > 1:
print(s.strip().split(' '))
So, my code doesn't do anything, i need to somehow find if any of the strings have at least 2 words and print all of those words.
Perhaps loop through the list and split each string. Then determine if the resulting sum is greater than 1:
text_list = ['G', 'A', 'B', 'C D', 'E']
for i in range(len(text_list)):
if len(text_list[i].split(' ')) > 1:
print(text_list[i])
Using list comprehension:
x = [w for w in text_list if len(w.split(' ')) > 1]
print(x)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.