将输入更改为标题,处理原始空间的问题

时间:2015-05-04 17:26:03

标签: 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

2 个答案:

答案 0 :(得分:0)

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

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.isdigit()仅包含数字,则True会返回s
  • 您可以使用s.strip()从输入中删除空格,如果您留下空字符串,''if not s将为True(空字符串相当于False

答案 1 :(得分:0)

在python 3中,您可以使用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')