-3
if __name__ == '__main__':
    string =[' \n            Boeing Vancouver\n          ', '\n          Airbus\n        ', '\n          Lockheed Martin\n        ', '\n          Rolls-Royce\n        ', '\n          Northrop Grumman\n        ', '\n          BOMBARDIER\n        ', '\n          Raytheon\n        ']
    for item in string:
        item.replace("\n"," ")
        item.strip()
    print(string)

the output is the same as the input, why?

Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170
iris
  • 13
  • 1

3 Answers3

0

You need to review the documentation again:

Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

In other words, item.replace("\n"," ") on its own does nothing.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

You can use a list comprehension like:

Code:

[s.replace("\n", " ") for s in a_string]

Test Code:

a_string = [' \n            Boeing Vancouver\n          ',
          '\n          Airbus\n        ',
          '\n          Lockheed Martin\n        ',
          '\n          Rolls-Royce\n        ',
          '\n          Northrop Grumman\n        ',
          '\n          BOMBARDIER\n        ',
          '\n          Raytheon\n        ']


print([s.replace("\n", " ") for s in a_string])

Results:

['              Boeing Vancouver           ', 
 '           Airbus         ', 
 '           Lockheed Martin         ', 
 '           Rolls-Royce         ', 
 '           Northrop Grumman         ', 
 '           BOMBARDIER         ', 
 '           Raytheon         ']
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
0

String are imutable in python. You can simply strip the leading or trailing whitespaces using list comprehension to make new list.

[x.strip() for x in string]
Rahul
  • 10,830
  • 4
  • 53
  • 88