我正在尝试在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)
。
如果你知道字符串确实包含下划线,你甚至可以将左右两侧拆分成单独的变量:
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()
函数。它的用法与上一个示例类似,不同的是它返回三个组件而不是两个。其主要优点是如果字符串中不包含分隔符,则该方法不会失败。
按空格拆分字符串,获取列表,显示其类型,将其打印出来:
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']
正则表达式"[a-m]+"表示匹配出现一次或多次的小写字母a到m作为定界符。需要导入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
如果左右两边始终是等分的,也可以使用内置在字符串中的 partition
方法。如果找到了分隔符,则返回一个三元组形式的 (LHS,separator,RHS)
,如果分隔符未出现,则返回 (original_string,'','')
:
>>> "2.7.0_bf4fda703454".partition('_')
('2.7.0', '_', 'bf4fda703454')
>>> "shazam".partition("_")
('shazam', '', '')
partition
方法,并更新你的问题。 - S.Lott