1

使用している一連のPython文字列がある場合、それは常に次の形式になります。

initialword_content

initialword常に同じ文字数になる部分を削除したいので、すべてのインスタンス_をスペースに変換したいのですcontentが、アンダースコアが含まれている可能性があるため、これを行う最も簡単な方法は何ですか?

4

3 に答える 3

3
strs = "initialword_content"
strs = strs[12:].replace("_", " ")
print strs

イニシャルワードは常に同じ文字数であるため、文字列のサフィックスを取得できます。そして、string.replaceを使用して、すべての「_」をスペースに置き換えます。

于 2013-01-22T07:30:35.283 に答える
2

まず、文字列を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のソリューションを使用します。

于 2013-01-22T07:28:53.757 に答える
0

スライスと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'
于 2013-01-22T07:32:21.507 に答える