python - 在 Python 中获取子字符串

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

我有一个字符串 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]]

最简单的方法就是使用 splitrsplit :

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

关于python - 在 Python 中获取子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35263582/

相关文章:

JQuery 获取子字符串?

mysql - SQL - 查找以某个短语开头的所有单词

python - 二维网格的一维插值 ...

python - 建议一种在单击按钮时填充数据库的方法

python - self.arg = arg 和 self.__dict__ ['arg' ] = arg 在 Python 中的区别

python - python 中的 any() all() 函数

python - importlib.reload 是否应该在 Python 3.6 中恢复已删除的属性?

python - 通过索引将 numpy 数组中的值设置为 NaN

python - 将 Python DateTime 字符串转换为整数毫秒

javascript - 未捕获的类型错误 : Cannot use 'in' operator to search for '123' in