[英]Formatting multi line strings in Python
使用這個偽代碼:
1. 將數字聲明為浮點數
2. 聲明 Root 為 Float
3. 將響應聲明為字符
4. 寫Do you want to find the square root of a number?
5. Enter 'y' for yes, 'n' for no:
我編碼的內容:
Response = str(input('Do you want to find the square root of a number? \
Enter y for yes, n for no: '))
PyCharm 運行窗口中的輸出:
你想找到一個數的平方根嗎? 輸入 y 表示是,輸入 n 表示否:
想要的格式結果:
Do you want to find the square root of a number?
Enter y for yes, n for no:
您可以使用\\n
打印換行符。
例子:
Response = input('Do you want to find the square root of a number?\nEnter y for yes, n for no: ')
輸出:
Do you want to find the square root of a number?
Enter y for yes, n for no:
你快到了。 您只是在嘗試打印的字符串中遺漏了一個 '\\n'。 這將以正確的格式打印您的字符串:
Response = str(input('Do you want to find the square root of a number?\nEnter y for yes, n for no: '))
你可以使用一個newline
作為所述的性格@MikeScotty
,或者你可以先用定義消息multi-line
string
。 這使得更改和創建消息比一遍又一遍地輸入\\n
更容易。
為此,請使用triple-quoted
strings
:
m = """Do you want to find the square root of a number?
Enter y for yes, n for no: """
然后你可以簡單地做:
input(m)
這將提示用戶:
Do you want to find the square root of a number?
Enter y for yes, n for no: [their entry ready here]
當然,您不需要單獨定義m
(消息),您可以直接將triple-quoted
string
寫為input
的參數,但事情可能會開始變得有點混亂:
Response = input("""Do you want to find the square root of a number?
Enter y for yes, n for no: """)
您需要添加\\n
而不僅僅是\\
。 N 代表“新行”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.