[英]how to get second last and last value in a string after separator in python
在Python中,如何獲取string中的倒數第二個元素? 字符串"client_user_username_type_1234567"
預期輸出: "type_1234567"
嘗試這個 :
>>> s = "client_user_username_type_1234567"
>>> '_'.join(s.split('_')[-2:])
'type_1234567'
您也可以使用re.findall
:
import re
s = "client_user_username_type_1234567"
result = re.findall('[a-zA-Z]+_\d+$', s)[0]
輸出:
'type_1234567'
沒有set函數可以為您完成此操作,您必須使用Python所提供的功能以及我要提供的功能:
"_".join("one_two_three".split("_")[-2:])
步驟:
用通用分隔符“ _”分隔字符串
s.split( “_”)
對列表進行切片,以便使用負索引獲得最后兩個元素
s.split( “_”)[ - 2:]
現在您有了一個由最后兩個元素組成的列表,現在您必須再次合並該列表,以使其類似於原始字符串,並使用分隔符“ _”。
。 “_” 加入( “one_two_three” .split( “_”)[ - 2:])
就是這樣。 另一種調查方法是通過正則表達式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.