[英]how to get the last part of a string before a certain character?
我試圖在某個字符之前打印字符串的最后一部分。
我不太確定是否使用字符串.split()方法或字符串切片或其他東西。
這是一些不起作用的代碼,但我認為顯示邏輯:
x = 'http://test.com/lalala-134'
print x['-':0] # beginning at the end of the string, return everything before '-'
請注意,末尾的數字會有所不同,因此我無法從字符串末尾設置精確計數。
您正在尋找具有限制的str.rsplit()
:
print x.rsplit('-', 1)[0]
.rsplit()
從輸入字符串的末尾搜索拆分字符串,第二個參數限制它將拆分為一次的次數。
另一種選擇是使用str.rpartition()
,它只會分裂一次:
print x.rpartition('-')[0]
對於僅拆分一次, str.rpartition()
也是更快的方法; 如果你需要多次拆分,你只能使用str.rsplit()
。
演示:
>>> x = 'http://test.com/lalala-134'
>>> print x.rsplit('-', 1)[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rsplit('-', 1)[0]
'something-with-a-lot-of'
與str.rpartition()
相同
>>> print x.rpartition('-')[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rpartition('-')[0]
'something-with-a-lot-of'
拆分和分區之間的區別是拆分返回沒有分隔符的列表,並將分割到字符串中的分隔符即可
x = 'http://test.com/lalala-134-431'
a,b,c = x.split(-)
print(a)
"http://test.com/lalala"
print(b)
"134"
print(c)
"431"
和partition將僅使用第一個分隔符划分字符串,並且只返回列表中的3個值
x = 'http://test.com/lalala-134-431'
a,b,c = x.partition('-')
print(a)
"http://test.com/lalala"
print(b)
"-"
print(c)
"134-431"
所以你想要最后一個值你可以使用rpartition它以相同的方式工作,但它會從字符串的末尾找到分隔符
x = 'http://test.com/lalala-134-431'
a,b,c = x.partition('-')
print(a)
"http://test.com/lalala-134"
print(b)
"-"
print(c)
"431"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.