Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting a variable into a string (quote)

Help I can't get this to work, I am trying to put the variable age into the string but it won't load the variable properly.

Here is my code:

import random
import sys
import os


age = 17
print(age)
quote = "You are" age "years old!"

Gives this error:

File "C:/Users/----/PycharmProjects/hellophyton/hellophyton.py", line 9
        quote = "You are" age "years old!"
                        ^
SyntaxError: invalid syntax

Process finished with exit code 1
like image 951
Tim Avatar asked May 03 '16 22:05

Tim


People also ask

How do you put a variable in a quote?

When referencing a variable, it is generally advisable to enclose its name in double quotes. This prevents reinterpretation of all special characters within the quoted string -- except $, ` (backquote), and \ (escape).

How do you put a variable inside a string?

If you can depend on having Python >= version 3.6, then you have another attractive option, which is to use the new formatted string literal (f-string) syntax to insert variable values. An f at the beginning of the string tells Python to allow any currently valid variable names as variable names within the string.

How do you put a variable in a quote in Java?

You can add double quotes to a string variable by using escape character symbol “\”. Using this symbol will notify the JVM to ignore the extra quotes around the text. All that you need to do is to add “\” in-front of the text and \”” at the end.


2 Answers

You should use a string formatter here, or concatenation. For concatenation you'll have to convert an int to a string. You can't concatenate ints and strings together.

This will raise the following error should you try:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

Formatting:

quote = "You are %d years old" % age
quote = "You are {} years old".format(age)

Concatenation (one way)

quote = "You are " + str(age) + " years old" 

Edit: As noted by J.F. Sebastian in the comment(s) we can also do the following

In Python 3.6:

f"You are {age} years old"

Earlier versions of Python:

"You are {age} years old".format(**vars())
like image 107
Pythonista Avatar answered Nov 15 '22 14:11

Pythonista


This is one way to do it:

>>> age = 17
>>> quote = "You are %d years old!" % age
>>> quote
'You are 17 years old!'
>>> 
like image 29
Joe T. Boka Avatar answered Nov 15 '22 13:11

Joe T. Boka