Avi Shah
Avi Shah

Reputation: 109

More quotes in input method inside f string

I have a string:

print(f"Your name is {input("Your name: ")}")

Unfortunately, it gets confused the quotes. I tried this, but it gives a SyntaxError:

print(f"Your name is {input(\"Your name: \")}")

This works:

print(f"Your name is {input('Your name: ')}")

However I have a convention of using " over ' in this case, so you would you do this, using "?

Upvotes: 2

Views: 67

Answers (2)

Patrick Artner
Patrick Artner

Reputation: 51643

You could define the input message beforehand:

nmsg = "Your name: "
print(f"Your name is {input(msg)}") 

If just feel sorry for a single ' you can use 3 of them:

print(f"Your name is {input('''Your name: ''')}")

squinting really hard this looks almost like a ".

Any other way to remove the complete input statement or at least the string delimited by " from the print statement works as well:

def NameInput():
    return input('''Your name: ''')

print(f"Your name is {NameInput()}")

As pointed out in the comment: the cleanest way to do it would be to put the input statement before the print statement.

Upvotes: 0

ppwater
ppwater

Reputation: 2277

Backslashes cannot appear inside the curly braces {} Doing so results in a SyntaxError.

See this: https://www.python.org/dev/peps/pep-0498/#escape-sequences

So, Just do this like the third code:

print(f"Your name is {input('Your name: ')}")

Or just do this (like F.M pointed out in the comments):

name = input()
print(f"Your name is {name}")

Upvotes: 1

Related Questions