删除字符串引用而不切片?

时间:2014-03-05 18:56:18

标签: python

我想分析输入的字符串,但引号干扰了我的分析。如何在不使用切片/索引的情况下删除引号?是否有像引用的string.strip()或等效的简单表达式?谢谢伙伴们!

3 个答案:

答案 0 :(得分:2)

您可以执行以下操作之一:

string.strip("'") # strips single quotes away
string.strip('"') # strips double quotes
string.strip("'\"") # both single and double quotes. The double quote in the middle is 'escaped' by the backslash character

string = string.replace("'", "") # replaces single quotes in the string with nothing
string = string.replace('"', '') # for double quotes

答案 1 :(得分:1)

使用replace

string = "'hello'"

print(string.replace("'",""))
# hello

答案 2 :(得分:1)

strip完全符合您的目的。只要求它删除引用:

>>> string = "'hello'"
>>> print(string.strip("'"))
hello