2010-11-28 20 views
2

ここにはPython '#b9d9ff'という文字列があります。ハッシュ記号(#)を削除するにはどうすればよいですか?Pythonの文字列を変更する

+2

注目点:Pythonの文字列は不変です。 ''#b9d9ff '.replace('# '、' ') 'で返された文字列は、元のものの修正版ではなく、まったく新しいものです。 – nmichaels

答えて

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('#')を使用するか、気にしない場合。これは、ほとんどの自己記述である。)

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

は、厳密に言えば、あなたは、すべてのpythonで文字列を変更することはできません。文字列は不変型です。必要な変更を加えて新しい文字列を返すだけで十分であれば、それ以外の答えも同様です。変更可能な型が本当に必要な場合は、単一の文字列のリストを使用するか、arrayモジュールのarray.fromstring()またはarray.fromunicode()メソッドを使用するか、より新しいPythonバージョンのbytearray型を使用できます。

関連する問題