[英]How can i print these 2 string, one in a line and the other on another?
我需要在2個單獨的行中打印string_a和string_b
我嘗試將打印命令分成兩行,但它不起作用
print(string_a +
string_b)
對於我的情況,我不能打印兩個不同的東西
print(string_a)
print(string_b)
這基本上是我需要做的:
string_a = 'hello '
string_b = 'world'
print(string_a + string_b)
我想要它打印:
'hello
world'
但它只是打印:
'hello world'
你可以試試這個:
string1 = 'hello'
string2 = 'world'
print(string1, string2, sep='\n')
輸出:
hello
world
並且,如果您想以下面的格式打印輸出
'hello
world' (with quotes)
然后,試試這個:
print("'{}\n{}'".format(string1, string2))
由於沒有人建議使用python 3 f-string方式,我會添加另一個答案,因為我認為它是更好的解決方案,因為它是最新的,並且應該替換舊的python字符串格式,因為它更容易閱讀,並且具有更快的運行時間,然后是“”.format或%格式化。
string_a = 'hello'
string_b = 'world'
print(f'{string_a}\n{string_b}')
您需要在需要輸出換行符的位置添加換行符,否則Python不會自動換行
string_a = 'hello '
string_b = 'world'
print(string_a +'\n'+ string_b)
在中間填充換行可能是最簡單的:
print(string_a +"\n"+ string_b)
你可以嘗試在python中使用f string 。 我喜歡這種類型的字符串,因為它非常有用且易於閱讀
string_a = 'hello '
string_b = 'world'
print(f'{string_a} \n{string_b}')
這將打印:
hello
world
您甚至可以在{}
中為變量輸入數字,而不僅僅是字符串類型。 此外, \\n
代表換行符,它會打印到新行
您還可以使用"""
來獲得您的願望結果: -
string_a = 'hello '
string_b = 'world'
string_c = 'bye'
print(f"""{string_a} # To print anything on next line simplly go to the next line.
{string_b}
{string_c}""")
產量
hello
world
bye
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.