2

I want to add quotation marks around a string.

My code looks like this:

first_name = "albert"

last_name = "einstein"

message = "A person who never made a mistake never tried anything new."
    
print(f"{first_name.title()} {last_name.title()} once said, {message} ")

The output is:

Albert Einstein once said, A person who never made a mistake never tried anything new.

But I want the output to be:

Albert Einstein once said, "A person who never made a mistake never tried anything new".  
Woodford
  • 3,746
  • 1
  • 15
  • 29
newbsith
  • 21
  • 1
  • 2

3 Answers3

3

Simply change the code to

first_name = "albert"

last_name = "einstein"

message = '"A person who never made a mistake never tried anything new."'

print(f"{first_name.title()} {last_name.title()} once said, {message} ")

Use single quotes around the original string, to make the other quotes - "" shown.

You could also use a slash - \. This acts as an escape sequence.

print(f"{first_name.title()} {last_name.title()} once said, \"{message} \" ")
krmogi
  • 2,588
  • 1
  • 10
  • 26
2

There are two methods to do this:

  1. You can escape the double quotes so something like: Putting a backslash behind the double quotes escapes it and takes it as part of the string instead of the endpoint
print(f"{first_name.title()} {last_name.title()} once said, \"{message} \" ")
  1. The other way is to use single quotes for f, then you can use double quotes unescaped
print(f'{first_name.title()} {last_name.title()} once said, "{message}" ')
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Keerthi Vasan
  • 63
  • 1
  • 7
  • And as someone else mentioned you can use the same escaping within double quotes / using single quotes for the message variable and put the double quotes inside there too – Keerthi Vasan Oct 12 '21 at 05:38
1

The quotes need to be inserted explicitly in the string something like this

# Case-1
print(f"""{first_name.title()} {last_name.title()} once said, "{message}" """)

The outcome is

Albert Einstein once said, "A person who never made a mistake never tried anything new."

Since the quote appears after the ., hence the quotes should go into the message string

# Case -2
first_name = "albert"
last_name = "einstein"
message = '"A person who never made a mistake never tried anything new".'

print(f"{first_name.title()} {last_name.title()} once said, {message} ")

Notice that in first example, I have used tripple quotes """ to enclose the string and in second case, its double quotes " inside single '. Many such combinations work in python. Otherwise writing the message like below also works, but requires escaping the double quotes

message = "\"A person who never made a mistake never tried anything new\"."

Also have a look at these docs https://docs.python.org/3/tutorial/introduction.html#strings https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals

leangaurav
  • 393
  • 2
  • 11