我有一个返回字符串列表的函数。 我需要将字符串连接起来并以单个字符串的形式返回。
字符串列表:
data_hold = ['ye la AAA TAM tat TE
0042
on the mountain sta
nding mute Saw hi
m ply t VIC 3181',
'Page 2 of 3
ACCOUNT SUMMARY NEED TO GET IN TOUCH? ',
'YOUR USAGE BREAKDOWN
Average cost per day $1.57 kWh Tonnes']
我尝试将它们串联如下-
data_hold[0] + '\n' + data_hold[1]
实际结果:
"ye la AAA TAM tat TE\n0042\n\non the mountain sta\nnding mute Saw hi\nm ply t VIC 3181ACCOUNT SUMMARY NEED TO GET IN TOUCH? ',\n'YOUR USAGE BREAKDOWNAverage cost per day $1.57 kWh Tonnes'\n
预期结果:
'ye la AAA TAM tat TE
0042
on the mountain sta
nding mute Saw hi
m ply t VIC 3181',
'Page 2 of 3
ACCOUNT SUMMARY NEED TO GET IN TOUCH? ',
'YOUR USAGE BREAKDOWN
Average cost per day $1.57 kWh Tonnes'
答案 0 :(得分:1)
您的“预期结果”不是一个字符串。但是,运行print('\n'.join(data_hold))
将产生等效的单个字符串。
答案 1 :(得分:0)
您误解了字符串的实际值,print()
时打印的内容与Python如何表示字符串以在屏幕上显示其值之间的区别。
例如,取一个字符串,其值为:
One line.
Another line, with a word in 'quotes'.
因此,该字符串包含单个文本,包含两行,并且该字符串的某些部分用相同的引号引起来,以标记该字符串的开头和结尾。
在代码中,可以使用多种方法构造此字符串:
one_way = '''One line
Another line, with a word in 'quotes'.'''
another_way = 'One line\nAnother line, with a word in \'quotes\'.'
运行此命令时,会发现one_way
和another_way
包含与打印时完全相同的字符串,就像上面的示例文本一样。
Python,当您要求它向您显示代码中的表示形式时,实际上会向您显示与another_way
代码中指定的字符串类似的字符串,只是它更喜欢使用双引号显示它以避免避免转义单引号:
>>> one_way = '''One line
... Another line, with a word in 'quotes'.'''
>>> one_way
"One line\nAnother line, with a word in 'quotes'."
比较:
>>> this = '''Some text
... continued here'''
>>> this
'Some text\ncontinued here'
请注意,如果字符串本身中没有单引号,Python将如何决定使用单引号。而且如果两种引号都在里面,它将像上面的示例代码一样逃脱:
>>> more = '''Some 'text'
... continued "here"'''
>>> more
'Some \'text\'\ncontinued "here"'
但是在打印时,您会得到期望的结果:
>>> print(more)
Some 'text'
continued "here"