只需对字符串使用+
或+=
运算符,例如:
trailing_punct = ',' # can be '!','?',etc.
line1 += trailing_punct
# or
line1 = line1 + trailing_punct
+=
可用于修改字符串“ in place”(请注意,在幕后,它确实创建了一个新对象并分配给它,因此id(line1)
在此操作后将发生更改)
,
您的line1
和line2
似乎是字符串列表,所以我首先假设:
line1 = ["Moonlight","is","winter"]
line2 = ["The","waters","scent","fallen","snow"]
给定多个字符串参数以在单词之间添加空格时,您正在使用print
函数的默认行为:print(*line1)
等效于调用print(line1[0],line1[1],...)
(请参见*args and **kwargs )。
这使得将行分隔符添加到该行的单词列表中是不够的,因为它前面会有一个空格:
print("\n--//--\nUsing print default space between given arguments:")
line_separator = ","
line1.append(line_separator)
print(*line1)
print(*line2)
结果:
--//--
Using print default space between given arguments:
Moonlight is winter,The waters scent fallen snow
要完成的操作可以通过将单词列表连接到单个字符串中,然后将行列表与所需的分隔符连接起来来完成:
print("\n--//--\nPrinting a single string:")
line1_str = ' '.join(line1)
line2_str = ' '.join(line2)
line_separator = ",\n" # notice the new line \n
lines = line_separator.join([line1_str,line2_str])
print(lines)
结果
--//--
Printing a single string:
Moonlight is winter,The waters scent fallen snow
请考虑使用行列表以方便扩展,并且可能会使用分隔符列表以用于每行。
本文链接:https://www.f2er.com/3128122.html