如何从报废的数据中删除字符'\ n'和'xa0'但保留空格?

时间:2019-05-05 08:11:49

标签: python python-3.x

我报废了一些数据,并将字符串存储在列表中。但是字符串中包含奇怪的字符:

['\nBayern Munich   ',
 '\nWerder Bremen ',
 '\nHamburger SV ',
 '\nFC Schalke 04 ',
 '\nBay. Leverkusen ',
 '\nHertha BSC ',
 '\nBor. Dortmund ',
 '\n1.FC Nuremberg ',
 '\nVfB Stuttgart ',
 "\nBor. M'gladbach ",
 '\n1.FSV Mainz 05 ',
 '\nHannover 96 ',
 '\nArm. Bielefeld ',
 '\nE. Frankfurt \xa0 ',
 '\nVfL Wolfsburg ',
 "\n1.FC K'lautern ",
 '\n1. FC Köln \xa0 ',
 '\nMSV Duisburg \xa0 ']

我知道如何删除'\ n'和'\ xa0',但我认为我这样做的方法不是很舒服。我还想消除每个字符串末尾的空格,但将空格保留在中间。

实际上我删除了具有列表理解的字符:

team = [elem.replace('\n','').replace('\xa0','') for elem in team]
team

我得到以下结果:

['Bayern Munich   ',
 'Werder Bremen ',
 'Hamburger SV ',
 'FC Schalke 04 ',
 'Bay. Leverkusen ',
 'Hertha BSC ',
 'Bor. Dortmund ',
 '1.FC Nuremberg ',
 'VfB Stuttgart ',
 "Bor. M'gladbach ",
 '1.FSV Mainz 05 ',
 'Hannover 96 ',
 'Arm. Bielefeld ',
 'E. Frankfurt  ',
 'VfL Wolfsburg ',
 "1.FC K'lautern ",
 '1. FC Köln  ',
 'MSV Duisburg  ']

我真正想要的是:

['Bayern Munich',
 'Werder Bremen',
 'Hamburger SV',
 'FC Schalke 04',
 'Bay. Leverkusen',
 'Hertha BSC',
 'Bor. Dortmund',
 '1.FC Nuremberg',
 'VfB Stuttgart',
 "Bor. M'gladbach",
 '1.FSV Mainz 05',
 'Hannover 96',
 'Arm. Bielefeld',
 'E. Frankfurt',
 'VfL Wolfsburg',
 "1.FC K'lautern",
 '1. FC Köln',
 'MSV Duisburg']

有人可以解释如何消除每个字符串末尾的空格吗?问题是空格的数量在1-3之间。

2 个答案:

答案 0 :(得分:0)

在此处添加.strip()

>>> [elem.replace('\n','').replace('\xa0','').strip() for elem in team]
['Bayern Munich', 'Werder Bremen', 'Hamburger SV', 'FC Schalke 04', 'Bay. Leverkusen', 'Hertha BSC', 'Bor. Dortmund', '1.FC Nuremberg', 'VfB Stuttgart', "Bor. M'gladbach", '1.FSV Mainz 05', 'Hannover 96', 'Arm. Bielefeld', 'E. Frankfurt', 'VfL Wolfsburg', "1.FC K'lautern", '1. FC K\xc3\xb6ln', 'MSV Duisburg']

答案 1 :(得分:0)

您可以这样做:

[s.strip() for s in team]