0

I want to replace empty instances '' with '.' in list compare:

compare = ['ŋsbluː', 'mən', '', 'blˈyːt', '', 'ʔˈɛs']
compare = [w.replace('', '.') for w in compare]

Output: ['.ŋ.s.b.l.u.ː.', '.m.ə.n.', '.', '.b.l.ˈ.y.ː.t.', '.', '.ʔ.ˈ.ɛ.s.]'

But I want: ['ŋsbluː', 'mən', '.', 'blˈyːt', '.', 'ʔˈɛs']

Komi Sla
  • 41
  • 4

3 Answers3

2

You're calling replace on the individual elements in the list. You can accomplish the desired effect by filtering through the list:

compare = ['ŋsbluː', 'mən', '', 'blˈyːt', '', 'ʔˈɛs']
compare = ["." if x == "" else x for x in compare]
Benjamin Engwall
  • 294
  • 1
  • 11
2

compare = [i or '.' for i in compare]

Ali Aqrabawi
  • 143
  • 1
  • 14
1

What you really mean is compare = ['.' if w == '' else w for w in compare] rather than replace which would replace every zero-length substring in your code.

But then you don't really need a list comprehension because it could also be in-place.

for i, x in enumerate(compare):
    if x == '':
        compare[i] = '.'
Eli Korvigo
  • 10,265
  • 6
  • 47
  • 73
Blownhither Ma
  • 1,461
  • 8
  • 18