如何在for循环中合并这些字符串变量?

2024-09-29 21:48:03 发布

您现在位置:Python中文网/ 问答频道 /正文

string1 = "The wind, "
string2 = "which had hitherto carried us along with amazing rapidity, "
string3 = "sank at sunset to a light breeze; "
string4 = "the soft air just ruffled the water and "
string5 = "caused a pleasant motion among the trees as we approached the shore, "
string6 = "from which it wafted the most delightful scent of flowers and hay."

我试过:

for i in range(6): 
     message +=string(i)

但它没有工作,并显示错误:字符串未定义

我想直接操作变量,我知道把它们放在一个列表中要容易得多,但是想象一下,如果你有1000个字符串,那么写列表中的每一个都有点困难。你知道吗


Tags: andthe字符串which列表withuswind
3条回答

您正在使用不同的变量。您必须单独调用每个变量才能连接它们,因为您正试图像在列表中那样调用它们。尝试将它们添加到数组或列表中。你知道吗

如果你能把字符串放在一个列表中,那就更好了。否则:

for s in [string1, string2, string3, string4, string5, string6]:
    message += s

使用join()

cList = [string1, string2, string3, string4, string5, string6]

print("".join(cList))

我的建议是,不要使用n个变量,而是将它们列在一个列表中:

x = ["The wind, ", "which had hitherto carried us along with amazing rapidity, ", "sank at sunset to a light breeze; ", "the soft air just ruffled the water and ", "caused a pleasant motion among the trees as we approached the shore", "from which it wafted the most delightful scent of flowers and hay."]    

print("".join(x))

一行:

print("".join([string1, string2, string3, string4, string5, string6]))

相关问题 更多 >

    热门问题