Search code examples
pythonstringescapingstring-concatenation

Python: How to use Escape character to solve "SyntaxError: unexpected character after line continuation character"?


What I want to do:

I want to print the following message as output:

Hi "alias" your phone number is "1234567890" and your email ID is "foo@bar.foo"

Python Code

name= "alias"
phone= "1234567890"
email="foo@bar.foo"

print("Hi " + name + " your phone number is " + phone + " and your email ID is " + email)

This gives me the following output:

Hi alias your phone number is 1234567890 and your email ID is foo@bar.foo

But here double quote (" ") is missing.

What I tried to solve this:

print("Hi " + \" name \" + " your phone number is " + \" phone \"+ " and your email ID is " + \" email \")

Solution

  • Use str.format

    Ex:

    name= "alias"
    phone= "1234567890"
    email="foo@bar.foo"
    
    result = 'Hi "{}" your phone number is {} and your email ID is {}'
    print(result.format(name, phone, email))
    

    or f-string(py3.6)

    result = f'Hi "{name}" your phone number is {phone} and your email ID is {email}'
    print(result)