Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.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/4/string/5.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 如何在字符串中设置空格_Python_String_User Input - Fatal编程技术网

Python 如何在字符串中设置空格

Python 如何在字符串中设置空格,python,string,user-input,Python,String,User Input,我试图让程序检查用户输入的“起床”或“起床和发光”,然后让它打印“即时消息”。问题是它不会打印“im up”,而是直接转到else语句。我现在拥有的这段代码使得如果我将“get up”更改为“hello”,那么如果我在输入中输入任何东西并在输入中包含“hello”,它将打印“test”,如果可能的话,我希望保持这种方式?代码: dic = {"get,up", "rise,and,shine"} test = raw_input("test: ") tokens = test.split() i

我试图让程序检查用户输入的“起床”或“起床和发光”,然后让它打印“即时消息”。问题是它不会打印“im up”,而是直接转到else语句。我现在拥有的这段代码使得如果我将“get up”更改为“hello”,那么如果我在输入中输入任何东西并在输入中包含“hello”,它将打印“test”,如果可能的话,我希望保持这种方式?代码:

dic = {"get,up", "rise,and,shine"}
test = raw_input("test: ")
tokens = test.split()
if dic.intersection(tokens):
    print "test"
else:
    print "?" 
感谢您的帮助。

dic.intersection()
返回两个集合的交集。例如:

{1, 2, 3}.intersection({2, 3, 4})  # {2, 3}
您可能只想测试成员资格:

if tokens in dic:
    ...
虽然这也不起作用,因为你要用空格分隔字符串,这将使它测试单个单词,而不是整个短语。此外,为您的电视机命名
dic
也不是一个好主意。这是一套,不是字典

简而言之,不要使用集合,也不要使用
.split()


这段代码的问题是,如果我输入“hello get up”,它将不会打印测试,它将转到else语句。@user2458048:如果用户键入“up you get”,是否需要匹配?其中有两个词“get”和“up”,但顺序不同。此外,您只是希望短语中至少有一个单词(如“起床”)出现在输入中,还是希望短语中的每个单词都出现在输入中?如果至少出现一个单词,则交叉方法将返回一个真值。@JonathanLeffler:是否有方法获取这两个单词的正确顺序,例如有人输入“你能起来吗”?它会查找最重要的单词,即“起床”,并查看它们的顺序是否正确,然后打印“im up”@user2458048:我肯定有,但我对Python的了解有限。根据您的要求,套装和冰冻套装都不合适;集合不保持顺序。您可能需要将要搜索的短语存储为单词列表,输入也一样,您不仅要检查短语中的每个单词是否出现在输入中,还要检查第二个单词是否出现在第一个单词之后。
phrases = ['get up', 'rise and shine']
phrase = raw_input('Enter a phrase: ')

if phrase in phrases:
    print "test"
else:
    print "?"