【问题标题】:Not allowing spaces in string input Python不允许字符串输入Python中的空格
【发布时间】:2021-09-25 17:42:00
【问题描述】:

我试图在输入的字符串中不允许任何字符串。我已经尝试使用 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('')

【问题讨论】:

  • str.split 会在空格上分割——也许你可以利用它。你检查过文档吗? - docs.python.org/3/library/stdtypes.html#string-methods
  • 是的,我尝试拆分但无法正常工作。似乎脱衣舞可以有更好的含义,所以我选择了
  • str.count 怎么样?
  • 如果您的目标是删除空格,那么check this out
  • 我很确定我在 while True 循环中有冗余,导致它无法正确执行。它计算初始白色空格,但不计算输入单词之间的空格。所以我不知道改变那个 str.() 是否会改变任何东西

标签: python if-statement while-loop except


【解决方案1】:

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

例子:

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

main()

此代码将输出“HelloWorld!”

【讨论】:

  • 我想计算输入文本中的空格,如果空格 != 0 那么它会给他们一个错误,让他们再试一次并输入另一个字符串。这就是为什么我有 if len(no_spaces.strip()) == 0: 语句,因为我希望能够计算空格并且我的代码基于 # 执行
【解决方案2】:

此代码将只接受不包含任何空格的输入。

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

【讨论】:

  • 这解决了它。谢谢你。有点糟糕, .find 是正确的声明。我想知道我是否可以用 .strip 或 .split 完成它
  • 我相信 find 是解决这个问题的更好方法之一。在这里使用 strip 没有什么意义。但是可以像这样使用拆分:len(no_spaces.split(' ')) != 1:
  • 或者更简单:if ' ' in no_spaces:(即quote-space-quote
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-04
  • 2015-05-24
相关资源
最近更新 更多