【问题标题】:How to check if string contains only valid amount of spaces如何检查字符串是否仅包含有效数量的空格
【发布时间】:2021-11-09 04:49:44
【问题描述】:

我需要编写代码来检查某个输入字符串是否有效。它必须:

  1. 在输入字符串中包含一个用于分隔单词的“空格”
  2. 一行中不包含多个连续空格
  3. 不只包含一个“空格”(只 单个空格作为输入)。

这就是我的意思:

username = str(input())
print(username)

username = "two apples" # acceptable

username = "two apples and pears" # acceptable

username = "two' '' 'apples" # not acceptable (because of 2 spaces in a row or more)

username = " " # not acceptable (because of single space with no other words.) 

username = "' '' '' '' '' '' '" #not acceptable because of multiple spaces (didn't know how to type it in here better to clarify.

【问题讨论】:

  • if username == " " or " " in username: print("Invalid username")?
  • 是的,我试过了,但是如果用户名 == " " # 3 or 4 or5 或任何其他数量的空格,这将不起作用。
  • if username.contains(" ") #double space
  • @Swagrim .contains 是什么?
  • @YuraHardzeyevskyy 不,显然你没有尝试过。

标签: python python-3.x string


【解决方案1】:

我知道这可能与您直接要求的内容略有不同,但为什么不从用户名输入中去掉多余的空格呢?您可以使用正则表达式根据this answer 快速删除它们。

如果你只是想返回一个无效的输入,我会再次使用正则表达式。

import re

username = str(input("Please enter your username: "))
if re.search(" {2,}", username):
  print("Please do not include multiple spaces in a row in your username!")
else:
  # Do the rest of your program.

【讨论】:

  • 一个很好的建议,但是一个简单的in 条件,例如' ' in 'The quick brown fox',据我所知,它似乎是 Python 中最快的选项(甚至击败了正则表达式这个用例)
  • @rv.kvetch 这可能是真的,我并没有真正进行任何性能测试。虽然当我考虑剥离额外空间而不是仅仅检查空间是否存在时,正则表达式就在脑海中,所以我直接进入“只使用正则表达式进行搜索”。
  • 那个正则表达式不也能捕获单个空格吗?你的意思是" {2,}"
  • 我的意思是" {2,}",谢谢你的关注。
【解决方案2】:

我正在上在线课程,所以我不能准时上课。现在我可以给出答案了。

这是代码。也很容易理解。

username = input()
if ("  ") in username:
    print("Eh!")
elif username.isspace():
    print("Ew!")
else:
    print(username)

顺便说一句,你不需要在输入中使用 str(),因为它默认需要一个字符串输入。

【讨论】:

    【解决方案3】:

    我相信这是您正在寻找的代码。请使用不同的测试用例进行测试,如果有问题,请发表评论。我尝试了你所有的测试用例。

    def checkspace(string):
        if string:
            for idx,i in enumerate(string):
                try:
                    if (string[idx] == ' ' and string[idx+1] ==' '):
                        return 'String is Not Perfect'
                except:
                    return 'String is Not Perfect'
                
            print('String is Perfect')
        else:
            return 'No String At AlL'
    

    例如:

    string="two apples"
    checkspace(string)
      
    output:
    "String is Perfect"
    

    例如:

    string="two  apples"
    checkspace(string)
          
    output:
    "String is Not Perfect"
         
    

    【讨论】:

      猜你喜欢
      • 2011-01-25
      • 2011-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多