2016-04-22 158 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')