2016-04-22 156 views
2

我想將"Onehundredthousand"拆分爲"one""hundred""thousand"使用python。 我該怎麼做?將字符串拆分爲python中的單獨字符串

+1

post ur attempts .. –

+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

您可以使用一個字符串的partition方法將其分爲3個部分(左部分,分離器,右邊部分):

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