Home > Net >  How to remove spaces from list value in python?
How to remove spaces from list value in python?

Time:09-30

I have a python list like

my_list = [' LCD | Autorotation',
 '  S o u n d  ',
 ' Power | No Power | AC Adapter Not Powering System',
 ' Motherboard',
 ' LCD | Lines on Display',
 '  W i r e l e s s  ',
 '  D N S   F a i l u r e',
 ' Power | Battery | Swollen']

There is a space between the characters of list values. What should be the best way to remove these spaces my output should look like below

my_list = [' LCD | Autorotation',
 '  Sound  ',
 ' Power | No Power | AC Adapter Not Powering System',
 ' Motherboard',
 ' LCD | Lines on Display',
 '  Wireless  ',
 '  DNS   Failure',
 ' Power | Battery | Swollen']

CodePudding user response:

You could use a regex to match spaces between single letters and replace them with nothing:

import re

new_list = [re.sub(r'(?<=\b\w) (?=\w\b)', '', item) for item in my_list]
print(new_list)

Output:

[
 ' LCD | Autorotation',
 '  Sound  ',
 ' Power | No Power | AC Adapter Not Powering System',
 ' Motherboard',
 ' LCD | Lines on Display',
 '  Wireless  ',
 '  DNS   Failure',
 ' Power | Battery | Swollen'
]

Note: \w will also match digits and _. If that gives unintended results, just replace it with [a-zA-Z] in the regex i.e. (?<=\b[a-zA-Z]) (?=[a-zA-Z]\b).

  • Related