我们如何使用 Python 在字符串的开头去掉标点符号? [英] How can we strip punctuation at the start of a string using Python?

查看:57
本文介绍了我们如何使用 Python 在字符串的开头去掉标点符号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Python 去除字符串开头的各种标点符号.我的 list 包含字符串,其中一些以某种标点符号开头.以及如何从字符串中删除所有类型的标点符号?

例如:如果我的单词像 ,,gets,我想从单词中去除 ,,,我想要 gets作为结果.另外,我想从列表中去除空格数字.我已尝试使用以下代码,但没有产生正确的结果.

如果 'a' 是一个包含一些单词的列表:

for i in range (0,len(a)):a[i]=a[i].lstrip().rstrip()打印一个[i]

解决方案

您可以使用 strip():

<块引用>

返回带有前导和尾随字符的字符串的副本移除.chars 参数是一个字符串,指定了要删除的字符.

传递string.punctuation 将删除所有前导和尾随标点符号:

<预><代码>>>>导入字符串>>>字符串.标点符号'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'>>>l = [',,gets', 'gets,,', ',,gets,,']>>>对于 l 中的项目:... 打印 item.strip(string.punctuation)...得到得到得到

或者,lstrip() 如果您只需要删除前导字符,rstip() - 用于尾随字符.

希望有所帮助.

I want to strip all kinds of punctuation at the start of the string using Python. My list contains strings and some of them starting with some kind of punctuation. And how can I strip all type of punctuation from the strings?

For example: If my word is like ,,gets, I want to strip ,, from the word, and I want gets as the result. Also, I want to strip away spaces as well as numbers from the list. I have tried with the following code but it is not producing the correct result.

If 'a' is a list containing some words:

for i in range (0,len(a)):
      a[i]=a[i].lstrip().rstrip()
      print a[i]

解决方案

You can use strip():

Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed.

Passing string.punctuation will remove all leading and trailing punctuation chars:

>>> import string
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

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

Or, lstrip() if you need only leading characters removed, rstip() - for trailing characters.

Hope that helps.

这篇关于我们如何使用 Python 在字符串的开头去掉标点符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆