文字列のリストを返す関数があります。文字列を連結して、単一の文字列の形式で返す必要があります。
文字列のリスト:
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()
Pythonが文字列を表現して画面に値を表示する方法の違いを誤解しています。
たとえば、次の値の文字列を取得します。
One line.
Another line, with a word in 'quotes'.
したがって、文字列には2行の単一のテキストが含まれ、文字列の一部には、文字列の開始と終了をマークするために使用するのと同じ引用符が含まれています。
コードでは、この文字列を作成するさまざまな方法があります。
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"
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加