python - 有没有办法读取字符串并将字符串中的每个字母转换为另一个字符串中的项目?
问题描述
我有一串字母:x = "ABCDE"
我有一个包含另一组字母的字符串: y = "VWXYZ"
我一直试图解决的想法是获取原始字符串 x,并将第二个字符串 y 中第一个字母(“V”)的所有实例读取到 x 的第一个位置。然后用所有字母 y 对 x 的所有位置重复此操作。
尝试了几个不同的循环,但很难做到这一点。
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
推荐阅读
- java - 在 Java 中不使用任何凭据即可阅读 Google 电子表格
- arrays - 按单元格中的倒数第二个字母排序数据,然后是第一个 - Google Apps Script / Google Sheets
- git - Git 仅在 GitLab 中记录模棱两可的参数
- javascript - 如何在稍后通过视图文件包含的其他 js 文件中使用 laravel-mix 文件(webpack)中的 js 函数?
- c - 将裸机 ARM 的 Rust 代码正确编译为静态库和 x86_64 的二进制文件?
- javascript - 窗口(浏览器)和全局(Node.js)对象之间的区别
- python - 在python中对数据框中的列(日期时间)进行排序的最快方法
- php - 如何在页面加载之前放置加载图标
- amazon-web-services - 高山 linux 上的 awscli 版本 2
- reactjs - Axios 承诺值呈现始终“未定义”