[英]replace multiple strings in a list with a single string by knowing the index
[英]List of multiple strings to single string with same structure
我有一个返回字符串列表的函数。 我需要将字符串连接起来并以单个字符串的形式返回。
字符串列表:
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'
您的“预期结果”不是一个字符串。 但是,运行print('\\n'.join(data_hold))
将产生等效的单个字符串。
您误解了字符串的实际值是什么,如果您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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.