[英]How do I make an input to be printed in the same print as something else?
Python newbie here Python新手在这里
Example:例子:
name = raw_input("What is your name? >> ")
print("Nice to meet you : ")
print(name)
How do I make [name] to be in the same print as "Nice to meet you : "
?我如何让 [name] 与
"Nice to meet you : "
打印在同一张"Nice to meet you : "
?
There are a number of ways.有多种方法。 This is one:
这是一:
name = raw_input("What is your name? >> ")
print("Nice to meet you : " + name)
Result:结果:
Nice to meet you : Joe
This will not just do everything in one print statement, but will also have the benefit of printing everything on one line.这不仅可以在一个打印语句中完成所有操作,而且还具有在一行中打印所有内容的好处。 I assume that's what you would prefer.
我想这就是你想要的。 If not, here's the equivalent code to get exactly the same result as the code you give in your question:
如果没有,这是获得与您在问题中提供的代码完全相同的结果的等效代码:
name = raw_input("What is your name? >> ")
print("Nice to meet you : \n" + name)
Result:结果:
Nice to meet you :
Joe
Another option is to use the format
method on a string:另一种选择是对字符串使用
format
方法:
name = raw_input("What is your name? >> ")
print("Nice to meet you : {}".format(name))
Result:结果:
Nice to meet you : Joe
Using this method is more valuable when the variable to be added to the string is to be placed in the middle of the string.当要添加到字符串的变量要放在字符串的中间时,使用这种方法更有价值。 So you can do something like this:
所以你可以做这样的事情:
print("Nice to meet you {}. Have a nice day.".format(name))
Result:结果:
Nice to meet you Joe. Have a nice day.
Once you upgrade to a newer version of Python, the new cool way to do this, and the most concise, is with format strings.升级到更新版本的 Python 后,执行此操作的新方法很酷,而且最简洁,就是使用格式字符串。 Here's what that looks like:
这是它的样子:
print(f"Nice to meet you {name}. Have a nice day.")
Result:结果:
Nice to meet you Joe. Have a nice day.
There are many ways.有很多方法。 One elegant way (in Python 3.x) for example would be using an f-String:
例如,一种优雅的方式(在 Python 3.x 中)是使用 f-String:
name = raw_input("What is your name? >> ")
print(f"Nice to meet you: {name}.")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.