Paul
Paul

Reputation: 107

Replacing a character the first time it occurs in a list of strings

I want to replace the first equals sign in each line with a comma, and leave the second occurrence of an equals sign alone.

I have attempted a for loop in which I find the index of the character and replace it with a comma, but I cannot select the correct equals sign or replace it.

lines = ['Temp = 65   ;   Temperature = degrees Fahrenheit',
     'Mass = 15   ;   Mass = kilograms '
     ]



for line in lines:
    i = line.index('=')
    line.replace('i[1]' , ',')

Upvotes: 0

Views: 37

Answers (2)

wjandrea
wjandrea

Reputation: 32944

You can replace just the first occurrence with the str.replace count parameter set to 1.

As well, you cannot modify a string in-place. So the easiest alternative is to use a list comprehension.

lines = [
    'Temp = 65   ;   Temperature = degrees Fahrenheit',
    'Mass = 15   ;   Mass = kilograms '
    ]

lines = [s.replace('=', ',', 1) for s in lines]
print(lines)

Output:

['Temp , 65   ;   Temperature = degrees Fahrenheit', 'Mass , 15   ;   Mass = kilograms ']

Upvotes: 1

IronMan
IronMan

Reputation: 1960

You can limit the number of matches to be replaced with a maxreplace parameter of 1:

line = line.replace('=', ',', 1)

Upvotes: 3

Related Questions