python - 正则表达式:准确输入 4 位数字,检查输入的数字是否出现在前 10,000 个字符中
问题描述
任何人都可以请检查我的代码?
当用户正好输入 4 位数字时,检查输入的数字是否出现在文本文件(名称为“2.txt 的平方根”)的前 10,000 个字符(小数点后)中,并使用 .find 告诉用户其位置() 方法。
创建一个名为 inputted_number.txt 的新文件。修改代码,以便所有有效输入都保存在该文件中。该文件的内容应如下所示:
3210
3222
4771
我不知道如何使用 re.find(),是 re.search 吗?我的代码如下:
#import my file
myfile = open("sqroot2_10kdigits.txt")
txt = myfile.read()
myfile.close()
# while True block use re.find
while True:
try:
number = str(input("Enter four digits: "))
int(number)
if re.findall(r'\d\d\d\d',txt)) == True:
print(f'The digits {int(number} appear in the first 10,000 characters of the square root of 2.' )
print(f'They appear starting on the {starting position}th character after the decimal.' )
else :
print(f'Sorry, the digits {int(number)} do not appear in the first 10,000 characters of the square root of 2.')
#NO.5 新建文件
with open('inputted_number.txt.', 'w') as filehandle:
filehandle.write('\n')
任何人都可以检查我的代码!
解决方案
对于您所描述的内容,您不需要正则表达式。
txt = '2319871325876234897034589734527861' \
'3098623409862349856243598672354897' \
'2348776623534078459996505467097201'
while True:
number = input("Enter four digits (q to quit): ")
if number.lower() == 'q':
break
elif len(number) != 4 or not number.isdigit():
print("Please enter four numbers")
continue
pos = txt.find(number)
if pos > -1:
print(
f'The digits {number} appear in the first '
'10,000 characters of the square root of 2.'
f'They appear starting on the {pos}th '
'character after the decimal.'
)
else:
print(
f'Sorry, the digits {number} do not appear '
'in the first 10,000 characters of the '
'square root of 2.'
)
在这些变化中:
- 使用 str.find 不是正则表达式
- 无需将字符串转换为 str 或 int
- 强制转换为 int 会导致 0001 出现问题
- 添加了一些基本的验证、长度和数字
推荐阅读
- python - 如何随机选择没有重叠的numpy数组
- nestjs - 在 class-transformer 中执行隐式转换之前获取一个值
- c# - `GetReferencedAssemblies` 是 `AppDomain.CurrentDomain.GetAssemblies()` 的子集吗?
- c++ - 复制无状态对象(lambdas)的成本?
- angular - 从父组件模态ok按钮以角度提交子组件
- animation - 控制 a-frame-alongpath-component 上的动画
- excel - Excel随机数公式
- reactjs - React 状态总是返回初始值
- python - Phototour 数据集的平均值和标准差的计算
- node.js - Twilio 弹性呼叫任务类型