close

How to print variable inside quotation marks?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to print variable inside quotation marks in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to print variable inside quotation marks?

  1. How to print variable inside quotation marks?

    The advantage to using repr() is that quotes within the string will be handled appropriately. If you have an apostrophe in the text, repr() will switch to "" quotes.

  2. print variable inside quotation marks

    The advantage to using repr() is that quotes within the string will be handled appropriately. If you have an apostrophe in the text, repr() will switch to "" quotes.

Method 1

you can use format:

>>> s='hello'
>>> print '"{}"'.format(s)
"hello"

Learn about format here:Format

In 3x you can use f:

>>> f'"{s}"'
'"hello"'

Method 2

If apostrophes (“single quotes”) are okay, then the easiest way is to:

print repr(str(variable))

Otherwise, prefer the .format method over the % operator (see Hackaholic’s answer).

The % operator also works, even in Python 3 so far, but is intended to be removed in some future version.

The advantage to using repr() is that quotes within the string will be handled appropriately. If you have an apostrophe in the text, repr() will switch to "" quotes. It will always produce something that Python recognizes as a string constant.

Whether that’s good for your user interface, well, that’s another matter. With % or .format, you get a shorthand for the way you might have done it to begin with:

print '"' + str(variable) + '"'

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read