检查空格是否在字符串中 [英] Check if space is in a string
本文介绍了检查空格是否在字符串中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
' ' in word == True
我正在编写一个程序来检查字符串是否是单个单词.为什么这不起作用,有没有更好的方法来检查字符串是否没有空格/是单个单词..
解决方案
==
优先于 in
,因此您实际上是在测试 word ==真的
.
但是您根本不需要 == True
.if
需要 [something that evaluate to True or False] 并且 ' ' in word
将评估为真或假.所以,if ' ' in word: ...
就好了:
' ' in word == True
I'm writing a program that checks whether the string is a single word. Why doesn't this work and is there any better way to check if a string has no spaces/is a single word..
解决方案
==
takes precedence over in
, so you're actually testing word == True
.
>>> w = 'ab c'
>>> ' ' in w == True
1: False
>>> (' ' in w) == True
2: True
But you don't need == True
at all. if
requires [something that evalutes to True or False] and ' ' in word
will evalute to true or false. So, if ' ' in word: ...
is just fine:
>>> ' ' in w
3: True
这篇关于检查空格是否在字符串中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文