0

If a list looks like this:

['wo/od', 'axe/es']

and for replacing "/" with nothing "" I am using following code but its not working.

for lines in z:
    if lines == "/"
    lines.replace = ""

I am new to python Any help would be appreciated. I am also not allowed to hardcode it.

Hassan
  • 1
  • 1

3 Answers3

4

Assuming that z is a reference to your list and bearing in mind that Python strings are immutable you could do this:

z = ['wo/od', 'axe/es']

z = [s.replace('/', '') for s in z]
Albert Winestein
  • 7,031
  • 2
  • 4
  • 14
0

I can see you are using replace in wrong way it should be

z = ['wo/od', 'axe/es']

for lines in z:
    lines = lines.replace("/","")
    print(lines)
im_vutu
  • 424
  • 1
  • 9
  • The OP wants to update the list with the new values, not print them. – Thierry Lathuille Apr 19 '22 at 06:22
  • Yes I got it wrong. OP said they are not allowed to hardcode the given example. And the given example is referencing each elements in loop as line rather than updating the list. So I kept the loop. Anyway the right answer is already given by Lancelot, so I am just keeping my answer as it is if someone wants to work with elements keeping the list as it is. – im_vutu Apr 19 '22 at 07:08
0

Try this:

a = ['wo/od', 'axe/es']
for i, line in enumerate(a):
    a[i] = line.replace('/', '')
print(a)
Avinash
  • 852
  • 5
  • 18