如何在Python中获取字符串中字符的位置?
当前回答
使用numpy快速访问所有索引的解决方案:
string_array = np.array(list(my_string))
char_indexes = np.where(string_array == 'C')
其他回答
当字符串包含重复字符时会发生什么? 从我使用index()的经验来看,对于duplicate,你会得到相同的索引。
例如:
s = 'abccde'
for c in s:
print('%s, %d' % (c, s.index(c)))
将返回:
a, 0
b, 1
c, 2
c, 2
d, 4
在这种情况下,你可以这样做:
for i, character in enumerate(my_string):
# i is the position of the character in the string
一个字符可能在字符串中出现多次。例如,在一个字符串句子中,e的位置是1,4,7(因为索引通常从0开始)。但我发现find()和index()函数都返回字符的第一个位置。所以,这个问题可以这样解决:
def charposition(string, char):
pos = [] #list to store positions for each 'char' in 'string'
for n in range(len(string)):
if string[n] == char:
pos.append(n)
return pos
s = "sentence"
print(charposition(s, 'e'))
#Output: [1, 4, 7]
string.find(character)
string.index(character)
也许您想查看一下文档,以找出两者之间的区别。
只是为了完成,在这种情况下,我想在一个文件名中找到扩展名,以便检查它,我需要找到最后一个'。,在这种情况下使用rfind:
path = 'toto.titi.tata..xls'
path.find('.')
4
path.rfind('.')
15
在我的情况下,我使用以下,无论完整的文件名是什么工作:
filename_without_extension = complete_name[:complete_name.rfind('.')]
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]
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用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