0

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]' , ',')
Paul
  • 107
  • 8
  • 1
    Strings are immutable in Python and you cannot modify a character at a given position the way you seems to be trying. – norok2 Aug 02 '19 at 19:32
  • `'i[1]'` is literal. I'm not sure what you're trying to do there anyway since an int is not subscriptable. – wjandrea Aug 02 '19 at 19:37
  • Possible duplicate of [changing one character in a string in Python](https://stackoverflow.com/questions/1228299/changing-one-character-in-a-string-in-python) – norok2 Aug 02 '19 at 19:45

2 Answers2

3

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

line = line.replace('=', ',', 1)
IronMan
  • 1,854
  • 10
  • 7
1

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 ']
wjandrea
  • 28,235
  • 9
  • 60
  • 81