[英]Getting Substring in Python
我有一個字符串fullstr = "my|name|is|will"
,我想提取子字符串“name”。 我使用string.find
找到'|'的第一個位置 像這樣:
pos = fullstr.find('|')
它返回2作為'|'的第一個位置 。 我想從pos
位置打印子串直到下一個'|'。 有rsplit
功能,但它返回字符串右邊的第一個字符,因為有很多'|' 在我的字符串中。 如何打印子串?
您可以使用
fullstr.split("|")[1]
這將打破“|”處的字符串分開 標記並返回一個列表。 抓取第二個項目(列表為0索引,因此這是索引1)將返回所需的結果。
你仍然可以使用find
,找到|
第一個位置 和下一個:
fullstr = "my|name|is|will"
begin = fullstr.find('|')+1
end = fullstr.find('|', begin)
print fullstr[begin:end]
使用index
方式類似:
fullstr = "my|name|is|will"
begin = fullstr.index('|')+1
end = fullstr.index('|', begin)
print fullstr[begin:end]
另一種方法是找到所有出現的|
在您的字符串中使用re.finditer
並按索引切片:
import re
all = [sub.start() for sub in re.finditer('\|', fullstr)]
print fullstr[all[0]+1:all[1]]
您還可以查看re.search
:
import re
fullstr = "my|name|is|will"
print re.search(r'\|([a-z]+)\|', fullstr).group(1)
使用enumerate
有一種有趣的方式:
fullstr = "my|name|is|will"
all = [p for p, e in enumerate(fullstr) if e == '|']
print fullstr[all[0]+1:all[1]]
fullstr = "my|name|is|will"
fullstr.split('|')[1]
fullstr.rsplit('|')[1]
使用split()方法將字符串分解為一個字符。
fullstr.split('|') == ['my', 'name', 'is', 'will']
然后你想要的是:
fullstr.split('|')[1] == 'name'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.