简体   繁体   中英

How to print a name in quotes inside a message in Python?

I started this Python course today with no programming experience, and I can't figure this out (it's so easy but I can't seem to figure it out).

This is what the program should look like in the end:

What is your name? 3von

So you call yourself '3von' huh?

This is how I wrote it:

name = input("What is your name? ")

print('So you call yourself', (name), "huh?")

What I can't figure out is how to get the ' ' around the (name) without it turning into a string.

Any help is appreciated!

PS What are the (name) things called?

You need to either enclose the other strings with different quotes, or escape them. Also, the default separator for print() is a space, which you don't want in between the quotes and name . Use + to concatenate it together, and keep in mind that this means you'll need to add the necessary spaces explicitly.

Different quotes:

print("So you call yourself '" + name + "' huh?")

Escaped:

print('So you call yourself \'' +name + '\' huh?')

String formatting is also a good approach, although you'll still need to mind your quotes or use escapes:

print("So you call yourself '{}' huh?".format(name))

The {} will be replaced with name . String formatting has a powerful mini language and is a great tool to learn.

name here is what is called a "variable".

To substitute a variable into a string, the best thing to use is the format method on strings. See the examples in the documentation, linked above.

In your case, you'd use:

print "So you call yourself '{}' huh?".format(name)

The {} inside the string indicate the place where the substitution goes, and the arguments to format are the variables to put in that place.

Note that the quotes around the outside of the string here are double quotes, and the ones inside, which you want printed, are single quotes. Inside a double quoted string, single quotes are treated as part of the string, and vice-versa.

Assuming I'm reading your question correctly, you want the output to look like this:

So your name is '3von' huh?

To do this, you need to both contain your single quotes within double quotes and concatenate your strings using +, like so:

print("So your name is '" + name + "' huh?")

(name) is a variable, although I'm not sure that was what you were asking. And you don't need to put it in parentheses.

You can use string formating.

name = input("What is your name? ")

print("So you call yourself '%s' huh?" % name)

试试这个,您在寻找这个吗

print('So you call yourself '+name+ " huh?")

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