如何在Python中拆分和解析字符串?

时间:2011-04-21 20:02:01

标签: python string parsing split

我试图在python中分割这个字符串:2.7.0_bf4fda703454

我想在下划线_上拆分该字符串,以便我可以使用左侧的值。

3 个答案:

答案 0 :(得分:130)

"2.7.0_bf4fda703454".split("_")给出了一个字符串列表:

In [1]: "2.7.0_bf4fda703454".split("_")
Out[1]: ['2.7.0', 'bf4fda703454']

这会将字符串拆分为每个下划线。如果您希望在第一次拆分后停止,请使用"2.7.0_bf4fda703454".split("_", 1)

如果您知道该字符串包含下划线这一事实,您甚至可以将LHS和RHS解压缩到单独的变量中:

In [8]: lhs, rhs = "2.7.0_bf4fda703454".split("_", 1)

In [9]: lhs
Out[9]: '2.7.0'

In [10]: rhs
Out[10]: 'bf4fda703454'

另一种方法是使用partition()。用法与上一个示例类似,只是它返回三个组件而不是两个组件。主要优点是,如果字符串不包含分隔符,则此方法不会失败。

答案 1 :(得分:71)

Python字符串解析演练

在空格上拆分字符串,获取列表,显示其类型,打印出来:

el@apollo:~/foo$ python
>>> mystring = "What does the fox say?"

>>> mylist = mystring.split(" ")

>>> print type(mylist)
<type 'list'>

>>> print mylist
['What', 'does', 'the', 'fox', 'say?']

如果您有两个彼此相邻的分隔符,则假定为空字符串:

el@apollo:~/foo$ python
>>> mystring = "its  so   fluffy   im gonna    DIE!!!"

>>> print mystring.split(" ")
['its', '', 'so', '', '', 'fluffy', '', '', 'im', 'gonna', '', '', '', 'DIE!!!']

在下划线上拆分字符串并抓住列表中的第5项:

el@apollo:~/foo$ python
>>> mystring = "Time_to_fire_up_Kowalski's_Nuclear_reactor."

>>> mystring.split("_")[4]
"Kowalski's"

将多个空格折叠为一个

el@apollo:~/foo$ python
>>> mystring = 'collapse    these       spaces'

>>> mycollapsedstring = ' '.join(mystring.split())

>>> print mycollapsedstring.split(' ')
['collapse', 'these', 'spaces']

当你没有将参数传递给Python的split方法时,the documentation states:“连续空格的运行被视为一个单独的分隔符,如果字符串具有前导或结果,结果将在开头或结尾不包含空字符串尾随空格“。

抓住你的帽子男孩,解析正则表达式:

el@apollo:~/foo$ python
>>> mystring = 'zzzzzzabczzzzzzdefzzzzzzzzzghizzzzzzzzzzzz'
>>> import re
>>> mylist = re.split("[a-m]+", mystring)
>>> print mylist
['zzzzzz', 'zzzzzz', 'zzzzzzzzz', 'zzzzzzzzzzzz']

正则表达式“[a-m] +”表示出现一次或多次的小写字母am匹配为分隔符。 re是要导入的库。

或者,如果您想一次选择一项:

el@apollo:~/foo$ python
>>> mystring = "theres coffee in that nebula"

>>> mytuple = mystring.partition(" ")

>>> print type(mytuple)
<type 'tuple'>

>>> print mytuple
('theres', ' ', 'coffee in that nebula')

>>> print mytuple[0]
theres

>>> print mytuple[2]
coffee in that nebula

答案 2 :(得分:17)

如果它总是一个偶数的LHS / RHS分割,你也可以使用内置于字符串中的partition方法。如果找到分隔符,则返回3个元组(LHS, separator, RHS);如果分隔符不存在,则返回(original_string, '', '')

>>> "2.7.0_bf4fda703454".partition('_')
('2.7.0', '_', 'bf4fda703454')

>>> "shazam".partition("_")
('shazam', '', '')
相关问题