如何使用Python去除字符串开头的标点符号?

3
我想使用Python去掉字符串开头的所有标点符号。我的列表包含字符串,其中一些以某种标点符号开头。如何从这些字符串中去掉所有类型的标点符号呢?
例如:如果我的单词是像,,gets这样,我希望从单词中去掉,,,并将gets作为结果。同时,我还想从列表中去掉空格数字。我尝试了以下代码,但它没有产生正确的结果。
如果'a'是一个包含一些单词的列表:
for i in range (0,len(a)):
      a[i]=a[i].lstrip().rstrip()
      print a[i]

str.*strip() 不会自动知道你想要去除什么,如果你想去除默认以外的内容。 - Ignacio Vazquez-Abrams
7个回答

9
您可以使用 strip()

返回一个去除开头和结尾字符的字符串副本。chars参数是一个指定要删除的字符集的字符串。

传递 string.punctuation 将删除所有前导和尾随标点符号字符:
>>> import string
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

>>> l = [',,gets', 'gets,,', ',,gets,,']
>>> for item in l:
...     print item.strip(string.punctuation)
... 
gets
gets
gets

或者,如果您只需要删除前导字符,则使用 lstrip(),如果需要删除尾随字符,则使用 rstip()
希望这有所帮助。

如何在列表中去除空格 - user3254544
@user3254544,您可以将空格添加到要删除的字符“list”中:item.strip(string.punctuation + ' '),或者在调用 strip()之后再调用item.strip(string.punctuation).strip() - alecxe

2

lstriprstrip 中传入您想要删除的字符。

'..foo..'.lstrip('.').rstrip('.') == 'foo'

1

strip()在没有参数的情况下只能去除空格。如果你想去除其他字符,需要将其作为参数传递给strip函数。在你的情况下,应该这样做。

a[i]=a[i].strip(',')

1
从字符串列表中删除每个字符串开头的标点符号、空格和数字:
import string

chars = string.punctuation + string.whitespace + string.digits    
a[:] = [s.lstrip(chars) for s in a]

注意:它不考虑非ASCII标点、空格或数字。

0
for each_string in list:
    each_string.lstrip(',./";:') #you can put all kinds of characters that you want to ignore.

0
如果你只想从开头删除它,请尝试这个:
    import re
    s='"gets'
    re.sub(r'("|,,)(.*)',r'\2',s)

0
假设您想要删除包含字符串的列表中所有标点符号(无论其出现在哪里),这应该能够起作用:
test1 = ",,gets"
test2 = ",,gets,,"
test3 = ",,this is a sentence and it has commas, and many other punctuations!!"
test4 = [" ", "junk1", ",,gets", "simple", 90234, "234"]
test5 = "word1 word2 word3 word4 902344"

import string

remove_l = string.punctuation + " " + "1234567890"

for t in [test1, test2, test3, test4, test5]:
    if isinstance(t, str):
        print " ".join([x.strip(remove_l) for x in t.split()])
    else:
        print [x.strip(remove_l) for x in t \
               if isinstance(x, str) and len(x.strip(remove_l))]

test3 = ",,这是一个句子,它有逗号和许多其他 :-) 标点符号!!" 输出应该像这样:,这是一个句子,它有逗号和许多其他 :-) 标点符号!! - user3254544

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接