【问题标题】:Python TypeError: expected a string or other character buffer objectPython TypeError:期望一个字符串或其他字符缓冲区对象
【发布时间】:2017-04-18 07:15:59
【问题描述】:

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

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(最近一次调用最后一次):文件“replace.py”,第 5 行,在 print(line.replace('2010', randint(1990, 2020)).rstrip()) TypeError: expected a string or other character buffer object

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

"myDate" : "2010_02",

【问题讨论】:

  • 你的 json 文件中有空行吗?
  • @ettanany 没有黑线!每一行至少有一个字符。
  • @Mpondomise 试试我的解决方案

标签: python typeerror


【解决方案1】:

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

返回字符串 s 的副本 将所有出现的子字符串 old 替换为 new。如果可选 给出参数 maxreplace,第一个 maxreplace 出现是 换了。

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

改变:

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

到:

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

【讨论】:

    猜你喜欢
    • 2012-09-17
    • 1970-01-01
    • 2016-01-24
    • 2019-06-22
    • 2016-07-15
    • 1970-01-01
    • 2013-04-18
    相关资源
    最近更新 更多