简体   繁体   中英

How do I make an input to be printed in the same print as something else?

Python newbie here

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 : " ?

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:

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. 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:

name = raw_input("What is your name? >> ")
print(f"Nice to meet you: {name}.")

It's simple. All what you need to do is this :

name = input("What is your name? >> ")
print("Nice to meet you : ", name)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM