Yungpythonnoob
Yungpythonnoob

Reputation: 125

How can you print a variable in quotation marks?

favoriteword = input('Enter your word: ')
print('What is your favorite word?',favoriteword)
print(favoriteword,favoriteword,favoriteword,favoriteword,favoriteword,favoriteword,favoriteword,favoriteword,favoriteword,favoriteword,favoriteword,favoriteword)
print(favoriteword, 'does not even sound like a word anymore.')

How can I make it so that in line 4 it comes out as "___" does not even sound like a word anymore." If I put it as this below it doesn't work.

print('"favoriteword"', 'does not even sound like a word anymore.')

Also if I put line 2 into a loop how would I print it so that it prints on a single line?

for i in range(12):
    print(favoriteword)

Upvotes: 2

Views: 306

Answers (3)

Phydeaux
Phydeaux

Reputation: 2855

In Python 2.6 or above, you can use string.format:

print('"{}" does not even sound like a word anymore.'.format(favoriteword))

In lower versions, Ketzak's method will work.


To print multiple times on a single line, you want to prevent print from appending a newline.

In Python 3, use the end argument:

for i in range(12):
    print(favoriteword, end='')
print('')  # for newline

or in lower versions:

import sys

for i in range(12):
    sys.stdout.write(favoriteword)
print('')

Upvotes: 6

Thiago F. Pappacena
Thiago F. Pappacena

Reputation: 326

In python >= 3.6, you can use "f-string":

print(f'"{favoriteword}" does not even sound like a word anymore.')

See this link for more information about it.

Upvotes: 2

Ketzak
Ketzak

Reputation: 628

Use the Python interpolation operator if you can guarantee favoriteword will always be a string:

print('"%s" does not even sound like a word anymore.' % favoriteword)

Upvotes: 3

Related Questions