How to remove "n" of a string in python3?

Question:

if __name__ == '__main__':
    string =[' n            Boeing Vancouvern          ', 'n          Airbusn        ', 'n          Lockheed Martinn        ', 'n          Rolls-Roycen        ', 'n          Northrop Grummann        ', 'n          BOMBARDIERn        ', 'n          Raytheonn        ']
    for item in string:
        item.replace("n"," ")
        item.strip()
    print(string)

the output is the same as the input, why?

Asked By: iris

||

Answers:

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.

You can use a list comprehension like:

Code:

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

Test Code:

a_string = [' n            Boeing Vancouvern          ',
          'n          Airbusn        ',
          'n          Lockheed Martinn        ',
          'n          Rolls-Roycen        ',
          'n          Northrop Grummann        ',
          'n          BOMBARDIERn        ',
          'n          Raytheonn        ']


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

Results:

['              Boeing Vancouver           ', 
 '           Airbus         ', 
 '           Lockheed Martin         ', 
 '           Rolls-Royce         ', 
 '           Northrop Grumman         ', 
 '           BOMBARDIER         ', 
 '           Raytheon         ']
Answered By: Stephen Rauch

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]
Answered By: Rahul
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.