Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/git/25.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 - Fatal编程技术网

Python 检查字符串的所有字母之间是否有空格

Python 检查字符串的所有字母之间是否有空格,python,Python,嗨,我需要帮助来做这件事: 假设字符串只包含空格和小写字母,我需要检查字符串中的所有字母是否至少间隔一个空格。如果字符串跟在后面,则分开打印,否则不分开打印。 谢谢:这是非常粗糙的,不清楚您想要什么: s1 = "t his will fail" s2 = "t h i s s e p a d" def is_spaced(s): prev = s[0] result = "is spaced" for c in s[1:]: if not c.

嗨,我需要帮助来做这件事: 假设字符串只包含空格和小写字母,我需要检查字符串中的所有字母是否至少间隔一个空格。如果字符串跟在后面,则分开打印,否则不分开打印。
谢谢:

这是非常粗糙的,不清楚您想要什么:

s1 = "t his will fail"
s2 = "t h     i s s e p a d"

def is_spaced(s):
    prev = s[0]
    result = "is spaced"
    for c in s[1:]:
        if not c.isspace() and not prev.isspace():
            result = "not spaced"
            break
        prev = c

    return result

print(is_spaced(s1))
print(is_spaced(s2))
产出:

not spaced
is spaced


您可以使用isspace函数,它不接受任何参数,并返回true和false。如果要检查某个字符串之间是否有空格,请使用string.isspace将字符串拆分为空格,然后检查每个组件的长度

demo='a b c d ef'
if all([len(item)<2 for item in demo.split(' ')]):
    print('is separated')
else:
    print('not separated')
demo.split“”在空间上拆分列表。给出['a','b','c','d','ef']


[lenitem您可以将字符串拆分为一个空格列表,然后在单个命令中找出每个空格的最大长度。如果每个字符都是空格,则列表中每个元素的最大长度将为一个。如果同时有多个字母,则最大长度将大于1

lenmaxteststring.split“”,key=len

这就简单地变成了:

if len(max(teststring.split(' '), key=len)) == 1:
    print("is separated")
else:
    print("is not separated")

您的示例输入/输出是什么?请共享一个示例输入和您的预期输出。您必须提供一个您尝试过但不起作用的示例。如果您认为问题不清楚,请不要回答,投票关闭它,因为不清楚您的问题并最终在注释中询问详细信息Python已经内置了一个all函数,不需要numpy h谢谢你,我已经把numpy删掉了。