python 查找字符串中字符的位置,忽略该字符串中的特殊字符
python find position of characters in a string ignoring special characters in this string
我有一个字符串
s1='abcdebcfg'
并且由于某种原因相同的字符串添加了字符 ('-','.')
s2='..abcde--bc-fg'
我想映射一个字符的索引从 s1
到 s2
示例:s1:0 -->s2:2 , s1:5 -->s2:9 ...
您可以尝试这样的操作:
for i in len(s1):
j = s2.find(s1[i])
print "s1:",i,"-->s2:",j
您可以为每个 (s1,s2) 使用两个堆栈,索引作为键,字符作为值,然后从每个堆栈中弹出值,比较它们并生成所需的输出。
好的,这样的事情应该可行:
for i in range(len(s1)):
for j in range (i,len(s2)):
if s2[j]==s1[i]:
print "s1:",i,"-->s2:",j
break
我解决了:
计算 s1
中字符在位置 i
出现的次数,然后在 s2
中找到具有相同出现次数
的字符 s1[i]
def find_nth(needle,haystack, n):
start = haystack.find(needle)
while start >= 0 and n > 1:
start = haystack.find(needle, start+len(needle))
n -= 1
return start
for i in range(len(s1)) :
occurrence= s1[:i+1].count(s1[i])
j=find_nth(s1[i], s2, occurrence)
注意我找到了 find_nth here
我有一个字符串
s1='abcdebcfg'
并且由于某种原因相同的字符串添加了字符 ('-','.')
s2='..abcde--bc-fg'
我想映射一个字符的索引从 s1
到 s2
示例:s1:0 -->s2:2 , s1:5 -->s2:9 ...
您可以尝试这样的操作:
for i in len(s1):
j = s2.find(s1[i])
print "s1:",i,"-->s2:",j
您可以为每个 (s1,s2) 使用两个堆栈,索引作为键,字符作为值,然后从每个堆栈中弹出值,比较它们并生成所需的输出。
好的,这样的事情应该可行:
for i in range(len(s1)):
for j in range (i,len(s2)):
if s2[j]==s1[i]:
print "s1:",i,"-->s2:",j
break
我解决了:
计算 s1
中字符在位置 i
出现的次数,然后在 s2
中找到具有相同出现次数
s1[i]
def find_nth(needle,haystack, n):
start = haystack.find(needle)
while start >= 0 and n > 1:
start = haystack.find(needle, start+len(needle))
n -= 1
return start
for i in range(len(s1)) :
occurrence= s1[:i+1].count(s1[i])
j=find_nth(s1[i], s2, occurrence)
注意我找到了 find_nth here