[英]remove all characters from a string other than a specified list of indices python
I have two strings: 我有两个字符串:
strA='EEEEEE HHHH HHHHHHH'
and string B of equal size 和大小相等的字符串B
strB='AJKFKKJSNCKSJNFKSJASLOINCLAJ'
I want to create a third string strC
which only has the characters in strB
corresponding to a given character in strA
. 我想创建一个第三串
strC
其中只有中的字符strB
对应于给定字符strA
。
For example I am interested in position of characters in strB
corresponding to 'H' in strA
, the output should look like: 例如,我很感兴趣,在人物的位置
strB
上对应于“H” strA
,输出应该是这样的:
strC=' SJNF OINCLAJ'
with the gaps intact. 完好无损。
I tried this: 我尝试了这个:
def find(s, ch):
return [i for i, ltr in enumerate(s) if ltr == ch]
temp= find(strA,'H') The output is: temp = find(strA,'H')输出为:
temp= [11, 12, 13, 14, 21, 22, 23, 24, 25, 26, 27]
when I tried creating a new string, str_new
by doing the following: 当我尝试创建新字符串时,通过执行以下操作
str_new
:
str_new = strB[temp]
I get an error 我得到一个错误
How do I do this? 我该怎么做呢?
You can use zip
: 您可以使用
zip
:
strA='EEEEEE HHHH HHHHHHH'
strB='AJKFKKJSNCKSJNFKSJASLOINCLAJ'
strC = ''.join([' ' if b != 'H' else a for a, b in zip(strB, strA)])
Output: 输出:
' SJNF OINCLAJ'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.