2016-04-22 25 views
2

私は分割したい"Onehundredthousand""one""hundred""thousand"を使用してPython。 どうすればいいですか?文字列Pythonで別の文字列に分割

+1

投稿ur attempt .. –

+2

この特定の文字列の場合、n個の異なる解決策があります。しかし、一般的なソリューションが必要な場合は、いくつかの区切り文字が必要です。 –

答えて

5
>>> s = "Onehundredthousand" 
>>> s.replace('hundred', '_hundred_').split('_') 
['One', 'hundred', 'thousand'] 

これは指定された文字列でのみ機能します。

+1

ありがとうございました。 –

+0

交換して分割して使用しますか?パーティションを使う方が良いです。 –

+0

私は完全に同意します。 – AKS

4

正規表現re.splitを使用しています。あなたは、セパレータとしてキャプチャグループを使用している場合、それはまた、結果リストに含まれます:

>>> import re 
>>> re.split('(hundred)', 'Onehundredthousand') 
['One', 'hundred', 'thousand'] 
+0

ご協力ありがとうございます –

6

あなたは3部(左部分、セパレーター、右側の部分)に分割して、文字列のpartitionメソッドを使用することができます。

"onehundredthousand".partition("hundred") 
# output: ('one', 'hundred', 'thousand')