[英]Formatting multi line strings in Python
Using this Pseudocode:使用这个伪代码:
1. Declare Number As Float 1. 将数字声明为浮点数
2. Declare Root As Float 2. 声明 Root 为 Float
3. Declare Response As Character 3. 将响应声明为字符
4. Write Do you want to find the square root of a number?
4. 写
Do you want to find the square root of a number?
5. Write Enter 'y' for yes, 'n' for no:
5.
Enter 'y' for yes, 'n' for no:
What I have coded:我编码的内容:
Response = str(input('Do you want to find the square root of a number? \
Enter y for yes, n for no: '))
Output in PyCharm Run Window: PyCharm 运行窗口中的输出:
Do you want to find the square root of a number?你想找到一个数的平方根吗? Enter y for yes, n for no:
输入 y 表示是,输入 n 表示否:
Format Result wanted:想要的格式结果:
Do you want to find the square root of a number?
Enter y for yes, n for no:
You can print a line wrap with \\n
.您可以使用
\\n
打印换行符。
Example:例子:
Response = input('Do you want to find the square root of a number?\nEnter y for yes, n for no: ')
Output:输出:
Do you want to find the square root of a number?
Enter y for yes, n for no:
Your almost there.你快到了。 You just missed a '\\n' in your string that your trying to print.
您只是在尝试打印的字符串中遗漏了一个 '\\n'。 This prints your string in the right format:
这将以正确的格式打印您的字符串:
Response = str(input('Do you want to find the square root of a number?\nEnter y for yes, n for no: '))
You could use a newline
character as said by @MikeScotty
, or you could define the message first using a multi-line
string
.你可以使用一个
newline
作为所述的性格@MikeScotty
,或者你可以先用定义消息multi-line
string
。 This makes changing and creating the message easier than typing in \\n
over and over again.这使得更改和创建消息比一遍又一遍地输入
\\n
更容易。
To do this, use triple-quoted
strings
:为此,请使用
triple-quoted
strings
:
m = """Do you want to find the square root of a number?
Enter y for yes, n for no: """
and then you can simply do:然后你可以简单地做:
input(m)
Which would prompt the user with:这将提示用户:
Do you want to find the square root of a number?
Enter y for yes, n for no: [their entry ready here]
Of course, you don't need to define m
(the message) separately, you can just write that triple-quoted
string
directly as the parameter for input
, but things can start to get a bit messy:当然,您不需要单独定义
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: """)
You need to add \\n
not just \\
.您需要添加
\\n
而不仅仅是\\
。 N represent the 'new line'. N 代表“新行”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.