在Python中修改字符串

时间:2010-11-28 21:50:04

标签: python string

我在python'#b9d9ff'中有一个字符串。如何删除哈希符号(#)?

3 个答案:

答案 0 :(得分:8)

有各种不同的选择。每个人对你的字符串做同样的事情,但处理其他字符串的方式不同。

# Strip any hashes on the left.
string.lstrip('#')

# Remove hashes anywhere in the string, not necessarily just from the front.
string.replace('#', '')

# Remove only the first hash in the string.
string.replace('#', '', 1)

# Unconditionally remove the first character, no matter what it is.
string[1:]

# If the first character is a hash, remove it. Otherwise do nothing.
import re
re.sub('^#', '', string)

(如果您不关心哪个,请使用lstrip('#')。这是最具自我描述性的。)

答案 1 :(得分:3)

>>> '#bdd9ff'[1:]
'bdd9ff'
>>> '#bdd9ff'.replace('#', '')
'bdd9ff'

答案 2 :(得分:2)

严格地说,你根本不能修改python中的字符串。字符串是不可变类型。如果它足以满足您的需要返回具有所需修改的新字符串,那么其他答案就是这样做的。如果你真的需要一个可变类型,你可以使用单个字符串的列表,或者你可以使用array模块的array.fromstring()array.fromunicode()方法,或者在较新的python版本中,{ {1}}输入。