提问人:Fainthearted Fox 提问时间:9/17/2023 最后编辑:Fainthearted Fox 更新时间:9/18/2023 访问量:100
为字符串中不存在的特殊字符返回 ValueError 的代码
Code returning ValueError for special characters in string that do not exist
问:
更新:
t作为参考,我正在使用 Jupyter 笔记本来运行这些,如果有人可能知道这里发生了什么。标题已编辑。
感谢您的所有评论。当我接触不同的人时,我被告知我忘记预先初始化变量,这通常会返回一个(但由于某种原因没有)。我还从原始字符串中分离出来,因此我不再需要检查每个循环。string_of_six
NameError
3.
x > 1
此代码片段来自一个代码,旨在读取包含一百万个 pi 数字的文本文件,然后将所有六位连续数字提取到一个列表中(包括非唯一模式,以及789012等)。
with open('pi_million_digits.txt', 'r') as file:
pi_file = file.read(100)
for x in range(len(pi_file)):
if x > 1 and x < (len(pi_file) - 5):
string_of_six = pi_file[x:x+6]
cons_check = []
for digit in string_of_six:
cons_check.append(int(digit))
print(cons_check)
当我运行仅读取前 100 个字符的代码时,会出现此错误(文本文件中有不可见的 s,但第一个超过 100 个字符。\n
ValueError Traceback (most recent call last)
Cell In[84], line 20
18 cons_check = []
19 for digit in string_of_six:
---> 20 cons_check.append(int(digit))
21 print(cons_check)
23 # converts string into int and puts them in a list
ValueError: invalid literal for int() with base 10: '\n'
试图找出导致错误的原因。ValueError: invalid literal for int() with base 10: '\n'
以下是我尝试过的一些事情:
with open('pi_million_digits.txt', 'r') as file:
pi_withn = file.read(50)
pi_file = pi_withn.replace('\n', '')
print(file.read(50))
使用 replace 尝试将 \n 替换为 nothing,则会出现相同的错误。
print(pi_withn)
和print(pi_file)
两者都返回以下内容 - 同一行上的所有字符。3.141592653589793238462643383279502884197169399375
还打开了txt文件进行检查。前 100 个字符中没有换行符。
答: 暂无答案
评论
pi_txt_file = Path("pi_million_digits.txt")
pi_txt_file.write_text(requests.get("https://raw.githubusercontent.com/ehmatthes/pcc/master/chapter_10/pi_million_digits.txt").text)
pi_withn
[2, 1, 1, 7, 0, 6]
[3, 9, 9, 3, 7, 5]