gpt4 book ai didi

Python 类型错误 : expected a string or other character buffer object

转载 作者:太空宇宙 更新时间:2023-11-03 10:55:53 25 4
gpt4 key购买 nike

我将 JSON 文件中所有出现的 2010 替换为 1990 到 2020 之间的随机数。

import fileinput
from random import randint
f = fileinput.FileInput('data.json', inplace=True, backup='.bak')
for line in f:
print(line.replace('2010', randint(1990, 2020)).rstrip())

我收到这个错误:

Traceback (most recent call last): File "replace.py", line 5, in print(line.replace('2010', randint(1990, 2020)).rstrip()) TypeError: expected a string or other character buffer object

这是这种情况的一个例子:

"myDate" : "2010_02",

最佳答案

string.replace(s, old, new[, maxreplace])

Return a copy of string swith all occurrences of substring old replaced by new. If the optionalargument maxreplace is given, the first maxreplace occurrences arereplaced.

新值必须是字符串,但您传递的是 int 类型的值。

改变:

line.replace('2010', randint(1990, 2020)).rstrip())

到:

line.replace('2010', str(randint(1990, 2020))).rstrip()

关于Python 类型错误 : expected a string or other character buffer object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40948108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com