python - 检查字符串中的整数 - python

标签 python string python-3.x integer

我有一个询问用户姓名的程序:

while True:
try:
    name = str(input("Please enter your name > "))
except ValueError:
    print("Please enter a valid name")
    continue
else:
    break

我想阻止用户输入整数,但是上面的代码可以在字符串中接受整数。如何防止用户在字符串中输入整数?

最佳答案

首先,不要将 str 转换为 input 返回 str。来自 docs 的注释

The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that

将输入输入到 name 后,您可以有一个 if 条件。

name = str(input("Please enter your name > "))
if (re.search('\d',name)):
     print("Sorry your name contains a number")

别忘了 import re

关于python - 检查字符串中的整数 - python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29265837/

相关文章:

python - 用数据模型方法覆盖 * 和 ** 解包?

python - Mongodb 中聚合的有效方法

c - 使用 memcpy 和 strtoul 获取乱码而不是数字

mysql - 如何在本地设置谷歌云 SQL

python - Numpy:获取索引大于值且条件为真的数组

c++ - 为什么要为 "copy on write"的 const 成员函数返回一个代理类?

c - 如何在c中通过替换另一个字符串来返回一个字符串

Python 父子特定类结构

python - 使用 ffmpeg 调整大小后文件损坏

python - 如何从命令提示符运行 Pygame 零程序?