我有一个字符串 fullstr = "my|name|is|will"
,我想提取子字符串“name”。
我使用 string.find
找到 '|' 的第一个位置像这样:
pos = fullstr.find('|')
它返回 2 作为 '|' 的第一个位置.我想打印从 pos
位置到下一个 '|' 的子字符串。有 rsplit
功能,但它返回字符串右侧的第一个字符,因为有很多 '|'在我的字符串中。如何打印子串?
最佳答案
您仍然可以使用 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]
关于python - 在 Python 中获取子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35263582/