[英]Regex: inputs exactly 4 digits, check whether the inputted number appears in the first 10,000 characters
Anyone can please check my code?任何人都可以请检查我的代码?
When the user inputs exactly 4 digits, check whether the inputted number appears in the first 10,000 characters (after the decimal) of the text file(which name is "square root of 2.txt") and tell the user its position using.find() method.当用户正好输入4位数字时,检查输入的数字是否出现在文本文件(名称为“2.txt的平方根”)的前10,000个字符(小数点后)中,并告诉用户它的position using.find () 方法。
Make a new file called inputted_number.txt.创建一个名为 inputted_number.txt 的新文件。 Modify the code so that all the valid input is saved in that file.
修改代码,以便所有有效输入都保存在该文件中。 The contents of that file should look something like this:
该文件的内容应如下所示:
3210
3210
3222
3222
4771
4771
I don' know how to use re.find(), is that re.search?我不知道如何使用 re.find(),是 re.search 吗? My codes below:
我的代码如下:
#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 make a new file #NO.5 新建文件
with open('inputted_number.txt.', 'w') as filehandle:
filehandle.write('\n')
Anyone can check my code please!任何人都可以检查我的代码!
For what you are describing you do not need a regex.对于您所描述的内容,您不需要正则表达式。
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.'
)
Among the changes:在这些变化中:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.