gpt4 book ai didi

python - 如何在 Python 中将空格从一个字符串复制到另一个字符串?

转载 作者:太空狗 更新时间:2023-10-30 02:37:41 26 4
gpt4 key购买 nike

我需要一种方法将一个字符串的空格的所有位置复制到另一个没有空格的字符串。

例如:

string1 = "This is a piece of text"
string2 = "ESTDTDLATPNPZQEPIE"

output = "ESTD TD L ATPNP ZQ EPIE"

最佳答案

将适当的字符插入到占位符列表中,并在使用 str.join 后将其连接起来。

it = iter(string2)
output = ''.join(
[next(it) if not c.isspace() else ' ' for c in string1]
)

print(output)
'ESTD TD L ATPNP ZQ EPIE'

这是有效的,因为它避免了重复的字符串连接。

关于python - 如何在 Python 中将空格从一个字符串复制到另一个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49480642/

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