简体   繁体   中英

How to replace the first specific special character in each line by not touching the rest of that word in each of the line of a text file in python

How to replace the first word in a series of occurrences like below.

Im trying to replace the first "/" in each line(if present) with a "", if not present, go to the next line in a text file.

ex: in.txt

Stackover flow /abc/one/two
is suitable to search three/four/five
answers for all /six/seven/eight

output like:

Stackover flow abc/one/two
is suitable to search three/four/five
answers for all six/seven/eight

I have tried re.sub with various combinations but not able to get any suitable answers. I hope to find answers here. Thanks in advance.

You can split the string with "/" and join again ignoring the first split.

split = _str.split("/")
_new_str = split[0]+"/".join(split[1:])

If I understand the question correctly, you only try to change the first '/' when it's at the beginning of some list of options, eg '/abc/def/ghi', but not when it is between words, eg 'abc/def/ghi'.

This replaces '/' only if they are at the beginning of a word (per your example):

import re    

with open('in.txt', 'r') as input_file, open('out.txt', 'w') as output_file:
    for row in input_file:
        new_row = re.sub('\s/', ' ', row)
        output_file.write(new_row)

If you want to change the original file, I will refer you here which is quite a nice explanation of why it is not a good idea.

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