如何在Python中获取字符串中字符的位置?
当前回答
more_itertools。Locate是一个第三方工具,用于查找满足条件的项目的所有索引。
这里我们找到了字母“i”的所有索引位置。
鉴于
import more_itertools as mit
text = "supercalifragilisticexpialidocious"
search = lambda x: x == "i"
Code
list(mit.locate(text, search))
# [8, 13, 15, 18, 23, 26, 30]
其他回答
有两个字符串方法,find()和index()。两者之间的区别在于当没有找到搜索字符串时会发生什么。find()返回-1,index()引发ValueError。
使用find ()
>>> myString = 'Position of a character'
>>> myString.find('s')
2
>>> myString.find('x')
-1
使用指数()
>>> myString = 'Position of a character'
>>> myString.index('s')
2
>>> myString.index('x')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
来自Python手册
字符串。Find (s, sub[, start[, end]]) 返回s中子字符串sub所在位置的最低索引,使得sub完全包含在s[start:end]中。失败时返回-1。负值的开始和结束以及解释的默认值与切片相同。
And:
字符串。索引(s, sub[, start[, end]]) 类似于find(),但在未找到子字符串时引发ValueError。
string.find(character)
string.index(character)
也许您想查看一下文档,以找出两者之间的区别。
more_itertools。Locate是一个第三方工具,用于查找满足条件的项目的所有索引。
这里我们找到了字母“i”的所有索引位置。
鉴于
import more_itertools as mit
text = "supercalifragilisticexpialidocious"
search = lambda x: x == "i"
Code
list(mit.locate(text, search))
# [8, 13, 15, 18, 23, 26, 30]
为了完整起见,如果你需要找到字符串中某个字符的所有位置,你可以这样做:
s = 'shak#spea#e'
c = '#'
print([pos for pos, char in enumerate(s) if char == c])
这将打印:[4,9]
>>> s="mystring"
>>> s.index("r")
4
>>> s.find("r")
4
“冗长”的方式
>>> for i,c in enumerate(s):
... if "r"==c: print i
...
4
要得到substring,
>>> s="mystring"
>>> s[4:10]
'ring'
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- Printf与std::字符串?
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if