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

2024-04-19 10:31:56 发布

您现在位置:Python中文网/ 问答频道 /正文

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

user = "B B"

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

Tags: no字符串ifelseyes空格printuser
3条回答

你用的是^{},上面写着

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.

这里有一个简洁的方法来说明列表理解的灵活性。它是一个助手方法,检查给定字符串是否包含任何空格。

代码:

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

示例:

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

当然,可以对其进行扩展,以检查任何字符串是否包含任何集合中的元素(而不仅仅是空格)。前面的解决方案简洁明了,但有些人可能会说,它很难读懂,比下面这样的解决方案更不象话:

def contains_whitespace(s):
    for c in s:
        if c in string.whitespace:
            return True
    return False
def tt(w): 
    if ' ' in w: 
       print 'space' 
    else: 
       print 'no space' 

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

我在火车上,很抱歉没有解释。。不能键入太多。。

相关问题 更多 >