如何在Python中去掉字符串开头的标点符号?
我想用Python去掉字符串开头的所有标点符号。我的列表里有一些字符串,其中有些是以标点符号开头的。我该怎么做才能把这些字符串里的所有标点符号去掉呢?
举个例子:如果我的单词是,,gets
,我想把,,
去掉,最后只留下gets
。另外,我还想把空格和数字也从列表中去掉。我试过用以下的代码,但结果不太对。
假设'a'是一个包含一些单词的列表:
for i in range (0,len(a)):
a[i]=a[i].lstrip().rstrip()
print a[i]
7 个回答
0
for each_string in list:
each_string.lstrip(',./";:') #you can put all kinds of characters that you want to ignore.
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。
1
要从一个字符串列表中的每个字符串开头去掉标点符号、空格和数字,可以使用以下代码:
import string
chars = string.punctuation + string.whitespace + string.digits
a[:] = [s.lstrip(chars) for s in a]
注意:这个方法不考虑非ASCII字符的标点符号、空白字符或数字。
1
strip()
这个函数如果不加任何参数的话,只会去掉字符串两边的空格。如果你想去掉其他字符,就需要把这些字符作为参数传给这个函数。在你的情况下,你应该这样做:
a[i]=a[i].strip(',')
2
在 lstrip
和 rstrip
里传入你想要去掉的字符
'..foo..'.lstrip('.').rstrip('.') == 'foo'
10
你可以使用 strip()
方法:
这个方法会返回一个新的字符串,去掉开头和结尾的字符。你可以通过传入一个字符串来指定想要去掉的字符。
如果你传入 string.punctuation
,那么就会去掉所有开头和结尾的标点符号:
>>> import string
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> l = [',,gets', 'gets,,', ',,gets,,']
>>> for item in l:
... print item.strip(string.punctuation)
...
gets
gets
gets
另外,如果你只想去掉开头的字符,可以用 lstrip()
方法;如果只想去掉结尾的字符,可以用 rstrip()
方法。
希望这些信息对你有帮助。