簡體   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