pk.
pk.

Reputation: 99

How do I include quotation marks in a print statement if I am using a variable

word = input("Enter a word: ")
word_length = len(word)

print("The length of", word,"is ", word_length)

If word is 'back', the output will be:

The length of back is 4

I want the output to be:

The length of 'back' is 4

Upvotes: 1

Views: 460

Answers (2)

Bhargav Rao
Bhargav Rao

Reputation: 52071

The Good way:

The best way is to use format

print("The length of '{}' is {}".format(word, word_length))

The Bad way:

Using C-like statement, note that this is de-emphasised, (but not officially deprecated yet)

print("The length of '%s' is %s" % (word, word_length))

The Ugly way:

One way is to have your string add with a ' and using sep attribute

print("The length of '", word,"' is ", word_length, sep = '')

Upvotes: 5

nneonneo
nneonneo

Reputation: 179422

You can use repr of a word to include the Python quotation marks (as they appear in e.g. the interactive interpreter); this has the added benefit of working reasonably when quotes are already in the string:

print("The length of", repr(word), "is", word_length)

Upvotes: 0

Related Questions