gpt4 book ai didi

python - 有没有办法读取字符串并将字符串中的每个字母转换为另一个字符串中的项目?

转载 作者:行者123 更新时间:2023-12-01 07:17:39 24 4
gpt4 key购买 nike

我有一串字母: x =“ABCDE”

我有一个包含另一组字母的字符串: y =“VWXYZ”

我一直试图解决的想法是获取原始字符串x,并将第二个字符串y中的第一个字母(“V”)的所有实例读取到x的第一个位置。然后对 x 的所有位置和 y 的所有字母重复此操作。

尝试了几种不同的循环,但我很难得到正确的结果。

for i in range(len(x)):
print (x[i])
replaced = False

for z in range(len(y)):
x.replace(x[0],y[0])

输入字符串:

x = "ABCDE"
y = "VWXYZ"

理想情况下,结果将与每个序列一起打印在新行上。期望的结果:

"ABCDE" # starting sequence
"VBCDE" # replace first position in x with first position in y
"WBCDE" # replace first position in x with second position in y
"XBCDE" # replace first position in x with third position in y
"YBCDE"
"ZBCDE" # replace first position in x with fifth position in y
"AVCDE" # replace second position in x with first position in y
"AWCDE" # replace second position in x with second position in y
.......
"ABCDZ" # This would be the final sequence in the series.

所以基本上我希望生成改变序列的字符串,每个字符串都在新行上。

最佳答案

不要使用x.replace,它不会就地修改字符串,它会返回修改后的字符串(并且它将替换所有实例,而不仅仅是您想要替换的实例) ,您可以为此使用列表切片和字符串连接:

for i in range(len(x)):
for j in y:
print(x[:i] + j + x[i + 1:])

输出:

VBCDE
WBCDE
XBCDE
YBCDE
ZBCDE
AVCDE
AWCDE
AXCDE
AYCDE
AZCDE
ABVDE
ABWDE
ABXDE
ABYDE
ABZDE
ABCVE
ABCWE
ABCXE
ABCYE
ABCZE
ABCDV
ABCDW
ABCDX
ABCDY
ABCDZ

关于python - 有没有办法读取字符串并将字符串中的每个字母转换为另一个字符串中的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57868842/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com