我有一个字符串fullstr = "my|name|is|will"
,我想提取子字符串“名称”。我曾经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]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句