在Python中只允许使用字符? [英] Allow Only Alpha Characters in Python?

查看:187
本文介绍了在Python中只允许使用字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个程序,它的一部分需要输入一个名称。
名称只能是字母和空格(例如,John Smith),它不能是John Smith1
如果输入了无效字符,我需要程序显示错误消息并重新处理问题。我有一切,但验证。我猜这是这样的吗?

  name = str(input(What are the customers name? 
while True:
如果:
print(你输入了一个无效的字符,只输入名字。
name = str(input(What are the customers name?))
else:
break

有人可以填写 ??? .org / library / stdtypes.html#str.isalpharel =nofollow> isalpha() 字符串方法。



由于此人将输入带空格的名称,因此您有两个选项:


  1. (使用 split()

  2. 利用 string.letters

例如:

 >>> import string 
> > string.letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

''以获取允许的字符列表。因为这是家庭作业,其余由你决定。


I am writing a program, part of it requires the input of a name. The name can only be alpha and spaces (eg. John Smith) it cannot be John Smith1 If an invalid character IS entered, I need the program to display an error message and reask the questions. I have got everything but the validation. I'm guessing it goes something like this?

name = str(input("What is the customers name? "))
while True:
    if ??????????????????? :
        print("You have entered an invalid character. Enter only name."
        name = str(input("What is the customers name? "))
    else:
          break

Can someone please fill in the ?????s to make the program work?

解决方案

Try the isalpha() method of strings.

Since the person will enter names with spaces, you have two options:

  1. Split the input by the space (use split())
  2. Take advantage of string.letters

For example:

   >>> import string
   >>> string.letters
   'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

Combine that with a ' ' to get your list of allowed characters. Since this is homework, the rest is up to you.

这篇关于在Python中只允许使用字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆