How do you pass a variable in a double quote in python?

For those that are coming here while googling something like "python surround string" and are time conscientious (or just looking for the "best" solution).

I was going to add in that there are now f-strings which for Python 3.6+ environments are way easier to use and (from what I read) they say are faster.

#f-string approach
term = urllib.parse.quote(f"'{term}'")

I decided to do a timeit of each method of "surrounding" a string in python.

import timeit

results = {}

results["concat"] = timeit.timeit("\"'\" + 'test' + \"'\"")
results["%s"] = timeit.timeit("\"'%s'\" % ('test',)")
results["format"] = timeit.timeit("\"'{}'\".format('test')")
results["f-string"] = timeit.timeit("f\"'{'test'}'\"") #must me using python 3.6+
results["join"] = timeit.timeit("'test'.join((\"'\", \"'\"))")

for n, t in sorted(results.items(), key = lambda nt: nt[1]):
    print(f"{n}, {t}")

Results:

concat, 0.009532792959362268
f-string, 0.08994143106974661
join, 0.11005984898656607
%s, 0.15808712202124298
format, 0.2698059631511569

Oddly enough, I'm getting that concatenation is faster than f-string every time I run it, but you can copy and paste to see if your string/use works differently, there may also be a better way to put them into timeit than \ escaping all the quotes so let me know

Try it online!


Printing double quotes is tricky, as it itself is required as part of syntax to print the strings by surrounding them. In this article we will see how these double quotes can be printed using print statement.

The below scenarios will not print the double quote. The first two lines of code will give no output while the last one will through error.

Example

 Live Demo

print(" ")
print(" " " ")
print(""aString"")

Output

Running the above code gives us the following result −;

print(""aString"")
^
SyntaxError: invalid syntax

But if we surround the strings with proper quotes as shown below, then the quotes can themselves get printed. Enclosing double quotes within single quotes does the trick.

Example

 Live Demo

print('Hello Tutorialspoint')
print('"Hello Tutorialspoint"')

Output

Running the above code gives us the following result −

Hello Tutorialspoint
"Hello Tutorialspoint"

Using string variables

We can also use string formatting to print the double quotes as well as any other character which is part of the print syntax.

Example

 Live Demo

StringVar = 'Hello Tutorialspoint'
print("\"%s\""% StringVar )
print("\%s\"% StringVar )
print('"%s"' % StringVar )
print('"{}"'.format(StringVar))

Output

Running the above code gives us the following result −

"Hello Tutorialspoint"
\Hello Tutorialspoint\
"Hello Tutorialspoint"
"Hello Tutorialspoint"

How do you pass a variable in a double quote in python?

Updated on 26-Feb-2020 07:54:40

  • Related Questions & Answers
  • How to insert records with double quotes in MySQL?
  • Single quotes vs. double quotes in C or C++
  • Find records with double quotes in a MySQL column?
  • Single and Double Quotes in Perl
  • What is the difference between single and double quotes in python?
  • How to Convert Double to String to Double in Java?
  • What is the difference between single and double quotes in JavaScript?
  • Is there a PHP function that only adds slashes to double quotes NOT single quotes
  • How to use quotes correctly while using LIKE with search variable in MySQL in Java?
  • Print newline in PHP in single quotes
  • How to print concatenated string in Python?
  • How to convert the Integer variable to the string variable in PowerShell?
  • Print Single and Multiple variable in Python?
  • How to print a string two times with single statement in Python?
  • Triple Quotes in Python

You are welcome to go through our tutorials but please keep in mind that as we rely on community PRs for maintainance they may be out of date.

In this tutorial we are going to look at variables, user input and decision making.

Creating a variable

Python allows us to store data in something called variables so that we are able to use this data at a later point. To place an item in a variable we give it a name then set its value.

Now in the REPL type:

In this example you have now stored the value 2016 into the variable year. See what happens next when you type `year’ into the REPL. Does it show it back to you?

How about saving your age into a variable or your lucky number? Have a play around with storing numbers into variables.

Storing numbers in variables

Now that you are familiar with the use of variables, we are able to combine variables with the maths operations we learnt in the previous tutorial.

Now in the REPL type the following:

>>> revenue = 1000
>>> costs = 200
>>> profit = revenue - costs

Now type profit to see the results of this calculation.

Now work out the cost of running a codebar workshop if 60 people turned up and pizza cost £8 per 2 people?

Along with pizza, students and cost, what other variables can you think of that could go into this calculation?

Storing text in variables

As well as numbers variables are able to store text, known in Python as strings.

Now in the REPL type:

>>> name = 'codebar'
>>> url = "codebar.io"

Now type print(name) and print(url) to see these strings shown back to you. As you can see Python allows both single and double quotes to denote a string variable. Double quotes are required if there is going to be an apostrophe in the string.

For example:

Sometimes you will need to use an apostrophe within a single quote, on occasions like this it is recommended to use “string escaping”. This would look like:

Try storing a string within a variable without quotes, see what happens? Numbers do not require quotation marks, whereas they are mandatory for storing strings.

Now store some strings in variables that contain apostrophes and some that do not.

Types & casting

Python is what’s called a “typed language”. This is to say that there are multiple types of objects that you work with in Python, and they don’t all act the same way. The three types you’ve learnt so far are integers (int), floats (float), and strings (str). Integers are whole numbers, floats are numbers with a decimal point, and strings are any number of characters surrounded by either “” or ‘’. This is important to know because every Python programmer has tried to do this at least once in their career:

Go ahead and try this in your REPL, it explodes with a TypeError. You just tried to add a number to something that isn’t a number and Python doesn’t know how to do that. Additionally, the output of this may surprise you:

This tells Python to multiply a string by 8 so you get eight sevens rather than what you might expect. This is actually a very powerful feature of Python, but when you’re just starting out, it can be pretty confusing.

For now, all you really need to know is that if you have a string that you mean to treat like a number, you have to cast it that way. This is a string:

While this is a number:

This is an integer:

While this is a string:

Go ahead an experiment with int(), float(), and str(). You’ll need one of these for the final part of this tutorial.

Storing user input in variables

Now we are going to look at capturing user input using the python input command. Let’s create a variable in which to store the user input.

Now type this into your REPL:

>>> lucky_number = input("What is your lucky number? ")

Type back your answer after it asks you.

Now in the REPL type:

>>> food = input("What is your favourite food? ")

Now we are going to put your response into another variable.

Now try:

>>> my_name = input("What is your name? ")
>>> greeting = "Hello " + my_name

Then type greeting into your REPL to receive your message.

Decision making using variables

Now that we know how to use variables and know how to store data, let’s play around with decision making and changing prints based on your answer. In Python (and many other languages), one of the most common ways in which this is done is using an if statement. For example:

>>> number = 4
>>> if number > 3:
...     print("Bigger than three")
... elif number < 3:
...     print("Smaller than three")

Here we can see that if a number we have passed into this decision making code is bigger than three, we will receive a message telling us so. There is a different message if the number is smaller than three.

Also, now that we are getting more in depth with Python, we should say that Python is very particular about indentation (i.e. the spaces at the start of a line of code). With Python, if any lines are not indented correctly the code will not run. If you are running into bugs, this is a good place to start.

In this final exercise we are going to ask you the number of coffees you have drunk today and then change the statement returned to you, depending on your answer.

Let’s create a variable called coffee and put your coffee cup total into it:

>>> coffee = input("How many cups of coffee have you consumed today? ")

Now we’ll use some simple if/else logic to decide what to say about your drinking habits:

>>> if int(coffee) > 4:
...     print("You have a coffee problem")
... else:
...     print("You do not have a coffee problem")

Note the use of int() here to cast coffee as an integer. Without it, Python wouldn’t know how to properly compare coffee to 4. Try setting coffee to different numbers and then re-typing the if/else logic to see what comes out. Next you’ll learn about functions, so you’ll be able to do this without all the re-typing.

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

For Python, you might use '"' + str(variable) + '"' .

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 print a double quote variable?

Using \" escape sequence in printf, we can print the double quotes ("").

How do you pass a string with double quotes?

If you need to use the double quote inside the string, you can use the backslash character. Notice how the backslash in the second line is used to escape the double quote characters. And the single quote can be used without a backslash.