[英]how to find all asked characters or combinations in string
I want insert some text and find in this text some selected characters with index in sequence for each letter, for example 我想插入一些文本,并在此文本中找到一些选定的字符,每个字母依次带有索引,例如
all letters L
and O
in "hello world!" “ hello world”中的所有字母
L
和O
!
If you want the index for each characters use a defaultdict where the keys are the letters and the values are lists containing the index/indexes where that letter appears, you can get the index of each character using enumerate : 如果希望每个字符的索引使用defaultdict ,其中键是字母,值是包含该字母出现的索引的列表,则可以使用enumerate获取每个字符的索引:
s = "hello world!"
from collections import defaultdict
d = defaultdict(list)
for ind, ch in enumerate(s):
d[ch].append(ind)
Then to find the index lookup using the letter: 然后使用字母找到索引查找:
In [46]: d["o"]
Out[46]: [4, 7]
In [47]: d["l"]
Out[47]: [2, 3, 9]
If you just wanted the index for a particular letter you could use a list comp again using enumerate: 如果您只想要特定字母的索引,则可以使用枚举再次使用list comp:
inds = [ind for ind, ch in enumerate(s) if ch == "o" ]
For you while logic you need to go from index + 1: 对于逻辑而言,您需要从索引+ 1开始:
string.find('o', index + 1)
If you don't you will simply keep finding the same letter at the same index and loop infinitely. 如果不这样做,您将继续在相同的索引处查找相同的字母并无限循环。
If you want to replace letters, create a mapping with a dict and use dict.get
to do the replacing: 如果要替换字母,请使用dict创建映射,然后使用
dict.get
进行替换:
d = {"A": "E", "B": "X", "C": "M"}
s = "BACK"
print("".join([d.get(ch, ch) for ch in s]))
I agree with everything @Padraic Cunningham said (+1). 我同意@Padraic Cunningham所说的一切(+1)。 To change the letters of certain letters, you could make a function that makes use of the replace method.
要更改某些字母的字母,您可以创建一个使用replace方法的函数。
def modify(string):
string = string.lower() # changes all letters to lowercase
string = string.replace("a","e") # changes 'a' to 'e'
string = string.replace("b","x") # changes 'b' to 'x'
string = string.replace("c","m") # changes 'c' to 'm'
return string
>>> text = "Beyonce is awesome!"
>>> print text
Beyonce is awesome!
>>> text = modify(text)
>>> print text
xeyonme is ewesome!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.