【问题标题】:How to replace multiple items at once? [python]如何一次更换多个项目? [Python]
【发布时间】:2021-01-24 08:10:43
【问题描述】:

我想在一个文本文件上使用 make 替换

one two three pthree two ptwo one two ...(1000+ words)

这样的输出看起来像1 2 3 p3 2 p2 1 2 ....

我的代码看起来像

dict = { 'zero':'0','one':'1','two':'2','three':'3','four':'4','five':'5','six':'6','seven':'7'}
x = 'one two three pthree two ptwo one two' #reading input from file
for k, v in dict.items():
    x = x.replace(k, v)

我已经尝试过str.replaceregex 这些解决方案,但是这两种方法都给了我同样的错误

TypeError: replace() argument 2 must be str, not int

这个错误是什么意思?我应该如何解决它? 谢谢你

【问题讨论】:

  • 您发布的代码没有任何错误。
  • 是的,似乎工作正常,请参阅repl.it/@ChristianBauman/WoozyAggressiveUnix
  • TypeError: replace() argument 2 must be str, not int 这个错误只是告诉你需要输入str 类型,但你给它的是int。首先尝试使用str() 函数将其转换为str。可能您不只是提供有关您的问题的详细信息。
  • 另外,它会替换每一次出现。例如:'phone' 将是 'ph1',您可能没有预料到。

标签: python text replace


【解决方案1】:

运行您在问题中编写的代码确实有效。从错误中我怀疑您实际使用的字典更像是:

{ 'zero': 0, 'one': 1 } # etc

I.E 值是整数而不是字符串。您可以更正创建字典的任何内容以确保值具有正确的类型,或者您可以在调用 replace 之前强制转换为正确的类型

d = { 'zero': 0, 'one': 1, 'two': 2, 'three': 3 }
x = 'one two three pthree two ptwo one two' #reading input from file
for k, v in d.items():
    x = x.replace(k, str(v))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-30
    • 1970-01-01
    • 2014-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多