2010-11-28 30 views
2

我在python'#b9d9ff'中有一個字符串。我如何刪除哈希符號(#)?在Python中修改字符串

+2

值得指出的是:Python中的字符串是不可變的。用'#b9d9ff'.replace('#','')`取回的字符串不是原始的修改版本,而是一個全新的版本。 – nmichaels 2010-11-28 22:01:22

回答

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('#'),這是最自我描述。)在Python

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

嚴格地說,你不能修改字符串的。字符串是不可變的類型。如果您的需求足以滿足需要修改的新字符串,那麼其他答案就是這樣做的。如果您確實需要可變類型,則可以使用單個字符串列表,也可以使用array模塊的array.fromstring()array.fromunicode()方法,或者在較新的python版本中使用bytearray類型。