Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-查找特定字符串[至少2个单词]_Python_Arrays_Loops_Spacing - Fatal编程技术网

Python-查找特定字符串[至少2个单词]

Python-查找特定字符串[至少2个单词],python,arrays,loops,spacing,Python,Arrays,Loops,Spacing,另一个来自Python新手的问题 我有一个数组,用户可以输入5个不同的单词/句子,在用户输入这5个单词/句子后,用户再次输入5个文本中的一个,程序从数组中删除这个字符串,然后用户添加另一个字符串,它直接附加到Index=0 但是,当我想运行这个数组并查找数组中的任何字符串是否至少有2个单词时,问题就开始了 Text = [] for i in range(0, 5): Text.append(input('Enter the text: ')) print (Text) for

另一个来自Python新手的问题

我有一个数组,用户可以输入5个不同的单词/句子,在用户输入这5个单词/句子后,用户再次输入5个文本中的一个,程序从数组中删除这个字符串,然后用户添加另一个字符串,它直接附加到Index=0

但是,当我想运行这个数组并查找数组中的任何字符串是否至少有2个单词时,问题就开始了

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])
输出:

因此,我的代码没有任何作用,我需要以某种方式找到任何字符串是否至少有2个单词,并打印所有这些单词

所以,我的代码没有任何作用,我需要找到 字符串至少有2个单词,并打印所有这些单词

也许可以循环浏览列表并拆分每个字符串。然后确定结果总和是否大于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])
使用列表理解:

x = [w for w in text_list if len(w.split(' ')) > 1]
print(x)
在上面的代码中,s是完整的字符串,例如在您的示例中,s可以是'cd',而这个字符串不是空格

若要检查s是否有两个或多个可以使用的单词,请使用.split(“”),但在此之前,必须使用.strip()字符串从边框中删除空格

s = 'Hello World '
print(s.strip().split(' '))
>>> ['Hello', 'World']
在上面的示例中,s有两个空格,因此strip删除最后一个空格,因为它是一个边框空间,然后split将为您提供一个由空格分隔的字符串列表

因此,您的问题的解决方案可能是

for s in Text:
    if len(s.strip().split(' ')) > 1:
        print(s.strip().split(' '))

您是否正在尝试确定单个输入值是否为多个单词?如果是这样,函数split()将获取一个字符串并返回一个不带空格的字符串列表。示例:my_string=“hello world”.split()然后my_string=[“hello”,“world”]是的,非常感谢,现在它工作了,现在我明白了它的工作原理。
s = 'Hello World '
print(s.strip().split(' '))
>>> ['Hello', 'World']
for s in Text:
    if len(s.strip().split(' ')) > 1:
        print(s.strip().split(' '))