在Python中获取子串

时间:2016-02-08 06:29:00

标签: python python-2.7 substring python-2.x

我有一个字符串fullstr = "my|name|is|will",我想提取子字符串“name”。 我用string.find找到了'|'的第一个位置像这样:

pos = fullstr.find('|') 

并返回2作为'|'的第一个位置。我想打印从pos位置到下一个'|'的子串。有rsplit功能,但它返回字符串右边的第一个字符,因为有很多'|'在我的字符串中。如何打印子字符串?

3 个答案:

答案 0 :(得分:3)

您可以使用

fullstr.split("|")[1]

将在" |"标记并返回一个列表。抓取第二个项目(列表为0索引,因此这是索引1)将返回所需的结果。

答案 1 :(得分:3)

如果需要,您仍然可以使用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]]

使用splitrsplit的最简单方法:

fullstr = "my|name|is|will"
fullstr.split('|')[1]
fullstr.rsplit('|')[1]

答案 2 :(得分:2)

使用split()方法将字符串分解为一个字符。

fullstr.split('|') == ['my', 'name', 'is', 'will']

然后你想要的是:

fullstr.split('|')[1] == 'name'