它应该很容易,但我正在寻找一种有效的方法来执行它。
我知道我可以将字符串分成两部分并插入新值,但我试图用索引22-26替换每一行,如下所示:
line.replace(line[22:26],new_value)
问题
但是,该函数替换行中与line[22:26]的模式类似的所有内容。
在下面的示例中,我想将标记的数字1替换为数字17 :
结果如下。 注意在几个地方用17替换1 :
因此我不理解replace命令的行为。 对我做错了什么有简单的解释?
为什么我不想要RE
索引22-26之间的值在形式上不统一。
注意:我在Unix / Linux机器上使用python 3.5。
It should be very easy, but I am looking for an efficient way to perform it.
I know that I could split the string into two parts and insert the new value, but I have tried to substitute each line between the indexes 22-26 as follows:
line.replace(line[22:26],new_value)
The Problem
However, that function substitutes everything in the line that is similar to the pattern in line[22:26].
In the example below, I want to replace the marked number 1 with number 17:
Here are the results. Note the replacement of 1 with 17 in several places:
Thus I don't understand the behavior of replace command. Is there a simple explanation of what I'm doing wrong?
Why I don't want RE
The values between index 22-26 are not unified in form.
Note: I am using python 3.5 on Unix/Linux machines.
最满意答案
str.replace用字符串中的另一个替换1个子字符串模式。
例如
'ab cd ab ab'.replace('ab', 'xy') # produces output 'xy cd xy xy'同样,
mystr = 'ab cd ab ab' mystr.replace(mystr[0:2], 'xy') # also produces output 'xy cd xy xy'你可以做什么,只替换22-26位的字符
line = line[0:22] + new_value + line[26:]另外,查看您的数据,在我看来,它是一个固定宽度的文本文件。 虽然我的建议可行,但处理数据的一种更健壮的方法是在处理数据之前先读取并分离记录中的不同字段。
如果您可以访问pandas库,它提供了一个有用的功能,只是为了读取固定宽度的文件
str.replace replaces 1 sub-string pattern with another everywhere in the string.
e.g.
'ab cd ab ab'.replace('ab', 'xy') # produces output 'xy cd xy xy'similarly,
mystr = 'ab cd ab ab' mystr.replace(mystr[0:2], 'xy') # also produces output 'xy cd xy xy'what you could do instead, to replace just the characters in position 22-26
line = line[0:22] + new_value + line[26:]Also, looking at your data, it seems to me to be a fixed-width text file. While my suggestion will work, a more robust way to process this data would be to read it & separate the different fields in the record first, before processing the data.
If you have access to the pandas library, it provides a useful function just for reading fixed-width files
更多推荐
发布评论