微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

不允许在字符串输入 Python 中使用空格

如何解决不允许在字符串输入 Python 中使用空格

我试图在输入的字符串中不允许任何字符串。我试过使用 len strip 来尝试计算空格并且不允许它但它似乎只计算初始空格而不是输入字符串之间的任何空格。 这段代码的目的是:输入不允许空格。

虽然为真:

  try:
    no_spaces = input('Enter a something with no spaced:\n')
    if len(no_spaces.strip()) == 0:
        print("Try again")
        
    else:
        print(no_spaces)
        
 
except:
    print('')

解决方法

此代码只接受没有任何空格的输入。

no_spaces = input('Enter a something with no spaces:\n')
if no_spaces.count(' ') > 0:
    print("Try again")
else:
    print("There were no spaces")

交替使用

while True:
    no_spaces = input('Enter a something with no spaces:\n')
    if no_spaces.find(' ') != -1:
        print("Try again")
    else:
        print("There were no spaces")
        break

替代

while True:
    no_spaces = input('Enter a something with no spaces:\n')
    if ' ' in no_spaces: 
        print("Try again")
    else:
        print("There were no spaces")
        break
,

所以,如果我理解正确,您不希望字符串中有任何空格? strip() 只是删除开头和结尾的空格,如果您想删除字符串中的所有空格,您可以使用类似 replace 方法的方法。 Replace 将删除所有出现的字符并将它们替换为另一个(在这种情况下为空字符串)。

示例:

def main():
    myString = "Hello World!"
    noSpaces = myString.replace(" ","")
    print(noSpaces)

main()

此代码将输出“HelloWorld!”

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。