将输入更改为标题,处理原始空格时出现问题

2024-05-14 07:49:43 发布

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

因此,我对编程非常陌生,我正在尝试学习python作为入门

我试图创建一个可以做多种事情的函数(我将使用它来限制名称的输入)

  • 拒绝纯数字输入
  • 拒绝纯粹由空格构成的输入
  • 拒绝空输入
  • 将输入更改为标题

    def debugstr(inputa):
        inputa = inputa.replace(" ", "")
        try:
            int(inputa)
            inputb = debugstr(input("Invalid input, please enter Alphabetic strings only: "))
        except:
            if inputa == "":
                debugstr(input("Invalid input, please enter Alphabetic strings only: "))
            else:
                return inputa.title()
    

我遇到的问题是,当运行函数时,代码只会在第一次尝试时拒绝空白输入,如果某个内容被拒绝一次,并且用户再次输入一系列空格,那么它只会接受它作为输入

提前感谢您的时间!非常感谢:D


Tags: 函数名称onlyinput编程事情空格enter
2条回答

在Python3中,可以使用isinstance检查对象是否为字符串

word = input("Enter string: ")

def checkString(s):
   if isinstance(s, str):
      print('is a string')
   elif not s:
      print('empty')
   else:
      print('not a string')

更自然的处理方法(无需从内部调用相同的函数)是:

def make_title():

    def get_user_input():
        return input('Enter an alphabetic string: ')

    while True:
        s = get_user_input()
        s = s.strip()
        if not s:
            print('blank input!')
            continue
        if s.isdigit():
            print('contains only digits!')
            continue
        return s.title()

print(make_title())

一些注意事项:

  • 尽量不要重复(例如,代码中重复的错误消息)
  • Python包含许多有用的字符串方法,如果s只包含数字,则s.isdigit()返回True
  • 您可以使用s.strip()从输入中去除空白,如果留下空字符串,''if not s将是True(空字符串相当于False

相关问题 更多 >

    热门问题