-4

How to replace the exact string and not a part of the string, please?

l = ['1.5', '12.3', '.', 'A', '.', '.']
l = [i.replace('.', 'nan') for i in l]
print(l)

I obtain:

['1nan5', '12nan3', 'nan', 'A', 'nan', 'nan']

Desired result:

['1.5', '12.3', 'nan', 'A', 'nan', 'nan']
Carly
  • 107
  • 1
  • 7

1 Answers1

2

You aren't replacing in the string, your doing a string comparison

 ['nan' if i == '.' else i for i in l]
Sayse
  • 41,425
  • 14
  • 72
  • 139