简体   繁体   中英

replacing a character in a line of string

I have a .txt file with 20 lines. Each line carrying 10 zeroes separated by comma.

0,0,0,0,0,0,0,0,0,0

I want to replace every fifth 0 with 1 in each line. I tried .replace function but I know there must be some easy way in python

You can split the text string with the below command.

text_string="0,0,0,0,0,0,0,0,0,0"
string_list= text_string.split(",")

Then you can replace every fifth element in the list string_list using insert command.

for i in range(4,len(string_list),5):
    string_list.insert(i,"1")

After this join the elements of the list using join method

output = "".join([str(i)+"," for i in string_list])

The output for this will be :

'0,0,0,0,1,0,0,0,0,1,0,0,'

This is one way of doing

If text in this File follows some rule, you can parse it as CSV file, and change every fifth index and rewrite it to a new file.

But if you want to modify the existing text file, like replace the character then you can use seek refer to How to modify a text file?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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