繁体   English   中英

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

[英]How can I split and parse a string in Python?

我试图在python中拆分此字符串: 2.7.0_bf4fda703454

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

"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() 用法与上一个示例类似,只是它返回三个组件而不是两个组件。 主要优点是,如果字符串不包含分隔符,则此方法不会失败。

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方法时, 文档说明 :“连续空格的运行被视为单个分隔符,如果字符串具有前导或尾随空格,则结果将在开头或结尾处不包含空字符串”。

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

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

正则表达式“[am] +”表示出现一次或多次的小写字母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

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

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

>>> "shazam".partition("_")
('shazam', '', '')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM