outfile = open('outfile.txt', 'w')
for line in open('inputfile.txt'):
split_index = line.index('|')
line = line[:split_index] + '|BA' + line[:split_index]
outfile.write(line)
或者用split
outfile = open('outfile.txt', 'w')
for line in open('inputfile.txt'):
line = line.split('|')
line.insert(1, 'BA')
line = '|'.join(line)
outfile.write(line)
In [87]: str_ = 'AZ|C|DTD'
# Gets the partitions spitted on first `|`
# generates 3 element tuple: `('AZ', '|', 'C|DTD')`
In [88]: parts = str_.partition('|')
# Concatenate after joining first two elements with
# empty string, `BA|` and last element
In [89]: ''.join(parts[:2]) + 'BA|' + parts[2]
Out[89]: 'AZ|BA|C|DTD'
对于文件:
with open('file.txt') as f:
for line in f:
parts = line.strip().partition('|')
new_line = ''.join(parts[:2]) + 'BA|' + parts[2]
line.index('|')
给出第一次出现或者用split
使用
str.replace()
。你知道吗你不需要正则表达式。使用
str.partition
:对于文件:
相关问题 更多 >
编程相关推荐