简体   繁体   English

Python从.txt文件替换多个字符串

[英]Python replace multiple strings from a .txt file

I would like to use the .replace function to replace multiple strings with in a .txt file, to run my servos. 我想使用.replace函数将.txt文件中的多个字符串替换为运行我的伺服器。 My .txt looks like this: A5,0,500,1,400. 我的.txt如下所示:A5,0,500,1,400。

 data_dict = {} 

for line in data:

    line = line.replace("\n","","","")

    line_list = line.split(",")

    Object = line_list[0]
    num_one = line_list[1]
    num_two = line_list[2]
    num_three = line_list[3]
    num_four = line_list[4]


    data_dict[object] = [num_one, num_two, num_three, num_four]
    pass

return data_dict

The problem is here: line = line.replace("\\n","","","") 问题在这里:line = line.replace(“ \\ n”,“”,“”,“”)

This is the error: TypeError: replace() takes at most 3 arguments (4 given) 这是错误:TypeError:replace()最多接受3个参数(给定4个)

It works with line = line.replace("\\n","") but that is just one servo, I need to run two. 它与line = line.replace(“ \\ n”,“”)一起使用,但这只是一个伺服,我需要运行两个。

Thank you 谢谢

When you access replace as an instance method, you must only use 3 arguments. 当您访问replace作为实例方法时,必须仅使用3个参数。 The first argument (the string) is implicit. 第一个参数(字符串)是隐式的。 This is why you see the error. 这就是为什么您看到错误。

Further, you can use len(line) as a cheap way to replace all occurrences without knowing how many there are -- there can only be at most the number of characters in the string. 此外,您可以使用len(line)作为替换所有出现的廉价方法,而无需知道有多少个-字符串中最多只能有多少个字符。

line.replace("\n", "", len(line))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM