使用している一連のPython文字列がある場合、それは常に次の形式になります。
initialword_content
initialword
常に同じ文字数になる部分を削除したいので、すべてのインスタンス_
をスペースに変換したいのですcontent
が、アンダースコアが含まれている可能性があるため、これを行う最も簡単な方法は何ですか?
strs = "initialword_content"
strs = strs[12:].replace("_", " ")
print strs
イニシャルワードは常に同じ文字数であるため、文字列のサフィックスを取得できます。そして、string.replaceを使用して、すべての「_」をスペースに置き換えます。
まず、文字列を1回(パラメータ1からsplit
)に分割して、使い捨ての「initialword」と残りの部分を取得します。残りの部分では、すべてのアンダースコアをスペースに置き換えます。
s = 'initialword_content'
a, b = s.split('_', 1)
b = b.replace('_', ' ')
# b == 'content'
s = 'initialword_content_with_more_words'
a, b = s.split('_', 1)
b = b.replace('_', ' ')
# b == 'content with more words'
これは、1つのコマンドで実行できます。
s.split('_', 1)[1].replace('_', ' ')
別の方法:
' '.join(s.split('_')[1:])
または、「initialword」の長さが常に同じである場合(そして毎回計算する必要がない場合)、@JunHuのソリューションを使用します。
スライスとreplace()関数を使用しました。replace()は単に...置き換えます!
string = 'initialword_content'
content = string[12:] # You mentioned that intialword will always be the same length, so I used slicing.
content = content.replace('_', ' ')
例えば:
>>> string = 'elephantone_con_ten_t' # elephantone was the first thing I thought of xD
>>> content = string[12:]
>>> content
... con_ten_t
>>> content = content.replace('_', ' ')
>>> content
... con ten t
ただし、別の場所で「elephantone」も参照する場合は、次のようにします。
>>> string = 'elephantone_con_ten_t'
>>> l = string.split('_', 1) # This will only strip the string ONCE from the left.
>>> l[0]
... 'elephantone'
>>> l[1].replace('_', ' ')
... 'con ten t'