编辑字符串python正则表达式python

2024-05-15 00:10:49 发布

您现在位置:Python中文网/ 问答频道 /正文

list1= [u'%app%%General%%Council%', u'%people%', u'%people%%Regional%%Council%%Mandate%', u'%ppp%%General%%Council%%Mandate%', u'%Regional%%Council%', u'%chair%%Label%', u'%chairman%%Title%', u'%chairman%', u'%chairperson%']


list2=[u'app General Council', u'people', u'people Regional Council Mandate', u'ppp General Council Mandate', u'Regional Council', u'chair Label', u'chairman Title', u'chairman', u'chairperson']

我想将list1更改为list2以删除%replace as“”。 但是,当我使用以下语句时:

print [i.replace("%"," ") for i in list1]
[u' app  General  Council ', u' people ', u' people  Regional  Council  Mandate ', u' ppp  General  Council  Mandate ', u' Regional  Council ', u' chair  Label ', u' chairman  Title ', u' chairman ', u' chairperson ']

结果不是我想要的。 如何删除每个元素开头和结尾的空格?这样我就可以得到如清单2所示的结果


Tags: apptitlepeoplelabelreplacegeneralpppmandate
1条回答
网友
1楼 · 发布于 2024-05-15 00:10:49

您也可以尝试先用" "替换"%%",然后用""替换"%"。那会解决你的问题

In [18]: list2 = [i.replace("%%"," ") for i in list1]

In [19]: list2
Out[19]: 
[u'%app General Council%',
 u'%people%',
 u'%people Regional Council Mandate%',
 u'%ppp General Council Mandate%',
 u'%Regional Council%',
 u'%chair Label%',
 u'%chairman Title%',
 u'%chairman%',
 u'%chairperson%']

In [20]: list2 = [i.replace("%","") for i in list2]

In [21]: list2
Out[21]: 
[u'app General Council',
 u'people',
 u'people Regional Council Mandate',
 u'ppp General Council Mandate',
 u'Regional Council',
 u'chair Label',
 u'chairman Title',
 u'chairman',
 u'chairperson']

相关问题 更多 >

    热门问题