检查字符串中的空格(python)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26987222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:16:09  来源:igfitidea点击:

Checking whitespace in a string (python)

python

提问by Digi_B

Why do I always get YES!!!? I need to return NO!!!if the string contain a whitespace (newline, tap, space)

为什么我总是得到YES!!!NO!!!如果字符串包含空格(换行、点击、空格),我需要返回

user = "B B"

if user.isspace():
    print("NO!!!")
else:
    print("YES!!!")

采纳答案by doniyor

def tt(w): 
    if ' ' in w: 
       print 'space' 
    else: 
       print 'no space' 

>>   tt('b ')
>> space
>>  tt('b b')
>> space
>>  tt('bb')
>> no space

I am in train, sorry for not explaining.. cannot type much..

我在火车上,抱歉没有解释..不能打太多字..

回答by Hackaholic

user = 'B B'
for x in user:
    if x.isspace():
        print("no")
    else:print("yes")

you need to loop over it to check for all element, but the above code will not work as you expect.

您需要遍历它以检查所有元素,但是上面的代码不会像您期望的那样工作。

use a helper function:

使用辅助函数:

def space(text):
    if ' ' in text:
        return True
    else: return False

demo:

演示:

>>> ' ' in 'B B'
True
>>> ' ' in 'BB'
False

use into check

使用in检查

if you want to use isspace:

如果你想使用isspace

def space(text):
    for x in text:
        if x.isspace():
            return True
    return False

Instead of returning True or False you can return Desired string too:

您也可以返回 Desired 字符串,而不是返回 True 或 False:

>>> def space(text):
...     if ' ' in text:
...         return " yes Spaces"
...     else: return " No Spaces"
... 
>>> space('B B')
' yes Spaces'
>>> space('BB')
' No Spaces'

回答by Nilesh

You are using isspacewhich says

你正在使用isspace它说

str.isspace()

str.isspace()

Return true if there are only whitespace characters in the string and there is at least one character, false otherwise.

For 8-bit strings, this method is locale-dependent.

如果字符串中只有空白字符且至少有一个字符,则返回 true,否则返回 false。

对于 8 位字符串,此方法取决于语言环境。

回答by Duke

Here is a neat method that illustrates the flexibility of list comprehensions. It is a helper method that checks to see if a given string contains any whitespace.

这是一个很好的方法,说明了列表推导式的灵活性。它是一个辅助方法,用于检查给定的字符串是否包含任何空格。

Code:

代码:

import string
def contains_whitespace(s):
    return True in [c in s for c in string.whitespace]

Example:

例子:

>>> contains_whitespace("BB")
False
>>> contains_whitespace("B B")
True

This can, of course, be extended to check if any string contains an element in any set (rather than just whitespace). The previous solution is a neat, short solution, but some may argue it is hard to read and less Pythonic than something like:

当然,这可以扩展为检查任何字符串是否包含任何集合中的元素(而不仅仅是空格)。前面的解决方案是一个简洁、简短的解决方案,但有些人可能会认为它比以下内容更难阅读且 Pythonic 更少:

def contains_whitespace(s):
    for c in s:
        if c in string.whitespace:
            return True
    return False

回答by dawg

Since you are looking for more than just a simple ' 'where you could use ' ' in tgtyou can use any:

由于您正在寻找的不仅仅是一个简单的' '地方,' ' in tgt您可以使用任何

for s in ('B ', 'B B', 'B\nB', 'BB'):
    print repr(s), any(c.isspace() for c in s)

Prints:

印刷:

'B ' True
'B B' True
'B\nB' True
'BB' False

回答by Vietnhi Phuvan

In [1]: a<br>
Out[1]: ' b\t\n'

In [2]: (' ' in a)or('\t' in a)or('\n' in a)<br>
Out[2]: True

回答by Mad Physicist

You can use str.splitto check if a string contains spaces:

您可以使用str.split检查字符串是否包含空格:

>>> ''.split()
[]
>>> '  '.split()
[]
>>> 'BB'.split()
['BB']
>>> ' B '.split()
['B']
>>> 'B B'.split()
['B', 'B']

So you can check as

所以你可以检查为

def hasspace(x):
    if x:
        s = x.split()
        return len(s) == 1 and x == s[0]
    return False

If you are only trying to check for whole words in the string (i.e., you are not worried about surrounding spaces that could be removed by x.strip()), the condition x == s[0]is no longer necessary. The check becomes a single statement:

如果您只想检查字符串中的整个单词(即,您不担心周围的空格可能会被 删除x.strip()),x == s[0]则不再需要该条件。检查变成一个单一的语句:

def hasspace(x):
    return x and len(x.split()) == 1

Now you can do

现在你可以做

if hasspace(user):
    print("NO!!!")
else:
    print("YES!!!")