Add quotes to string python

Single, Double, and Triple Quotes in Python

It’s always good to have alternatives — single and double quotes are essentially used interchangeably in Python.

All of us Python programmers know that there is usage of single and double quotes related to the declaration of the strings in Python. However, not all of us know that there is certain usage involving triple quotes too.

This brief article reviews the usage of single, double, and triple quotes in Python.

Single and Double Quotes

Basic Usage

The most common use of single and double quotes is to represent strings by enclosing a series of characters. As shown in the code below, we create these two strings using single and double quotes, respectively.

>>> quotes_single = 'a_string'
>>> quotes_double = "a_string"
>>> quotes_single == quotes_double
True

As you notice, the strings created by using single and double quotes are the same. In other words, we can use single and double quotes interchangeably when we declare a string. However, it should be noted that we don’t want to mix them as it’s a syntactical error.

>>> "mixed quotes' 
File "", line 1
"mixed quotes'
^
SyntaxError: EOL while scanning string literal
>>> 'mixed quotes"
File "", line 1
'mixed quotes"
^
SyntaxError: EOL while scanning string literal

Escaping Behaviors

Like other programming languages, when a string contains special characters like quotes, we need to escape them. An example of failing to escape is shown below.

>>> 'It's a bad example.' 
File "", line 1
'It's a bad example.'
^
SyntaxError: invalid syntax

How can we fix this error? One is to escape the single quote by placing a backslash before it. The other is to use double quotes instead of single quotes as the enclosing quotes. Both ways are shown below.

>>> 'It\'s a good example.'
"It's a good example."
>>> "It's a good example."
"It's a good example."

Источник

Читайте также:  Create url in python

Add quotes to string python

Last updated: Jun 20, 2022
Reading time · 5 min

banner

# Table of Contents

# Add quotes to a string in Python

To add quotes to a string in Python:

  1. Alternate between single and double quotes.
  2. For example, to add double quotes to a string, wrap the string in single quotes.
  3. To add single quotes to a string, wrap the string in double quotes.
Copied!
# ✅ alternating single and double quotes result_1 = '"apple"' # ------------------------------------- # ✅ add double quotes around a variable my_str = 'hello world' result = f'"my_str>"' print(result) # 👉️ "hello world" # ------------------------------------- # ✅ add single quotes around a variable my_str = "hello" result = f"'my_str>'" print(result) # 👉️ 'hello' # ------------------------------------- # ✅ escaping double quotes with a backslash result_3 = "\"apple\""

add quotes to string in python

The first example in the code sample alternates between single and double quotes.

# Alternate between single and double quotes

If a string is wrapped in single quotes, we can use double quotes in the string without any issues.

However, if we try to use single quotes in a string that was wrapped in single quotes, we end up terminating the string prematurely.

If you need to add single quotes to a string, wrap the string in double quotes.

Copied!
result = "one 'two' three"

# Using a triple-quoted string

In some rare cases, your string might contain both single and double quotes. To get around this, use a triple-quoted string.

Copied!
result_1 = """ "one" two 'three' """

Triple-quotes strings are very similar to basic strings that we declare using single or double quotes.

But they also enable us to:

  • use single and double quotes in the same string without escaping
  • define a multiline string without adding newline characters
Copied!
example = ''' It's Alice "hello" ''' # # It's Alice # "hello" # print(example)

The string in the example above uses both single and double quotes and doesn’t have to escape anything.

End of lines are automatically included in triple-quoted strings, so we don’t have to add a newline character at the end.

# Add double or single quotes around a variable in Python

You can use a formatted string literal to add double or single quotes around a variable in Python.

Formatted string literals let us include variables inside of a string by prefixing the string with f .

Copied!
my_str = 'one' result = f'"my_str>" "two"' print(result) # 👉️ '"one" "two"'

add double or single quotes around variable

Notice that we still have to alternate between single and double quotes.

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f .

Copied!
my_str = 'is subscribed:' my_bool = True result = f'my_str> "my_bool>"' print(result) # 👉️ 'is subscribed: "True"'

Make sure to wrap expressions in curly braces — .

You can also use a backslash \ to escape quotes.

Copied!
result = "\"one\" \"two\"" print(result) # 👉️ '"one" "two"'

In most cases, it is preferable (and more readable) to alternate between single and double quotes, but escaping quotes can also be useful (e.g. in rare cases in a JSON string).

Notice that we wrapped the f-string in single quotes to be able to use double quotes inside of the string.

It is important to alternate between single and double quotes because otherwise you’d terminate the f-string prematurely.

If you have to print the variable in single quotes, wrap the f-string in double quotes.

Copied!
variable = 'bobbyhadz.com' result = f"'variable>'" print(result) # 👉️ 'bobbyhadz.com'

If you have to include both single and double quotes in the string, use a triple-quoted string.

Copied!
variable1 = 'bobbyhadz' variable2 = 'website' result = f"""'variable1>' "variable2>" """ print(result) # 👉️ 'bobbyhadz' "website"

If you need to have a double quote right next to the double quotes that terminate the triple-quoted string, escape it.

Copied!
variable1 = 'bobbyhadz' variable2 = 'website' result = f"""'variable1>' "variable2>\"""" print(result) # 👉️ 'bobbyhadz' "website"

Triple-quoted strings are very similar to basic strings that we declare using single or double quotes.

The string in the example uses both single and double quotes and doesn’t have to escape anything.

To print a variable inside quotation marks:

  1. Use the str.format() method to wrap the variable in quotes.
  2. Use the print() function to print the result.
Copied!
variable = 'bobbyhadz.com' result = '"<>"'.format(variable) print(result) # 👉️ "bobbyhadz.com"

print variable inside quotation marks using str format

The str.format method performs string formatting operations.

The string the method is called on can contain replacement fields specified using curly braces <> .

Make sure to provide exactly as many arguments to the format() method as you have replacement fields in the string.

You can also include the quotes in the variable declaration.

Copied!
variable = 'website "bobbyhadz"' print(variable) # 👉️ website "bobbyhadz"

Note that we used single quotes to wrap the string and double quotes inside of it.

Had we used single quotes inside of the string without escaping them, we’d terminate the string prematurely.

# Join a list of strings wrapping each string in quotes in Python

To join a list of strings wrapping each string in quotes:

  1. Call the join() method on a string separator.
  2. Pass a generator expression to the join() method.
  3. On each iteration, use a formatted string literal to wrap the item in quotes.
Copied!
my_list = ['one', 'two', 'three'] my_str = ', '.join(f'"item>"' for item in my_list) print(my_str) # 👉️ '"one", "two", "three"'

join list of strings wrapping each string in quotes

The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

Copied!
my_list = ['one', 'two', 'three'] print(', '.join(my_list)) # 👉️ 'one, two, three'

The string the method is called on is used as the separator between elements.

Copied!
my_list = ['one', 'two', 'three'] my_str = ' '.join(f'"item>"' for item in my_list) print(my_str) # 👉️ '"one" "two" "three"'

If you don’t need a separator and just want to join the iterable’s elements into a string, call the join() method on an empty string.

We used a formatted string literal to wrap each list item in quotes.

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f .

Make sure to wrap expressions in curly braces — .

The last step is to use a generator expression to iterate over the list of strings.

Copied!
my_list = ['one', 'two', 'three'] my_str = ', '.join(f'"item>"' for item in my_list) print(my_str) # 👉️ '"one", "two", "three"'

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

In the example, we iterated over the list and wrapped each item with quotes.

This approach also works if the list contains values of different types (e.g. integers).

Copied!
my_list = ['one', 'two', 'three', 4, 5] my_str = ', '.join(f'"item>"' for item in my_list) print(my_str) # 👉️ '"one", "two", "three", "4", "5"'

The join() method raises a TypeError if there are any non-string values in the iterable, but we take care of converting each list item to a string with the f-string.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

How to Quote a String in Python

To quote a string in Python use single quotation marks inside of double quotation marks or vice versa.

example1 = "He said 'See ya' and closed the door." example2 = 'They said "We will miss you" as he left.' print(example1) print(example2)
He said 'See ya' and closed the door. They said "We will miss you" as he left.

Python Strings

Python strings are sequences of characters and numbers.

A string is wrapped around a set of single quotes or double quotes. There is no difference in which you use.

Anything that goes inside the quotes is interpreted as being “text” instead an executable command.

To demonstrate, here are some examples.

print("10 + 20") # Prints: 10 + 20 print("This # is not a comment") # Prints: This # is not a comment print("pow(2,3)") # Prints: pow(2, 3)

In each example, there is a Python operation that would normally execute. But because the expression is wrapped inside a string, the expression is printed out as-is.

But here is where it gets interesting. Let’s see what happens when you place a double quote inside a string:

print("This "test" causes problems")
File "example.py", line 1 print("This "test" causes problems") ^ SyntaxError: invalid syntax

This happens because the Python interpreter sees a string of the expression in three parts:

It sees two strings and a reference to a non-existent object test . Thus it has no idea what to do.

To come over this issue, you have two options:

  1. Use single quotes inside double quotes (and vice versa).
  2. Escape the quotes inside a string with a backslash.

1. Single Quotes inside Double Quotes

To write a quoted string inside another string in Python

  • Use double quotes in the outer string, and single quotes in the inner string
  • Use single quotes in the outer string and double quotes in the inner string
example1 = "He said 'See ya' and closed the door." example2 = 'They said "We will miss you" as he left.' print(example1) print(example2)
He said 'See ya' and closed the door. They said "We will miss you" as he left.

But what if this is not enough? What if you want to have quotes inside quotes?

Then you need to resort to what is called escape sequences. These make it possible to add as many quotes in a string as you want.

2. How to Escape Quotes in a String

To add quoted strings inside of strings, you need to escape the quotation marks. This happens by placing a backslash ( \ ) before the escaped character.

In this case, place it in front of any quotation mark you want to escape.

example1 = "This is a \"double quote\" inside of a double quote" example2 = 'This is a \'single quote\' inside of a single quote' print(example1) print(example2)
This is a "double quote" inside of a double quote This is a 'single quote' inside of a single quote

How to Use a Backslash in a String Then

In Python, the backslash is a special character that makes escaping strings possible.

But this also means you cannot use it normally in a string.

To include a backslash in a string, escape it with another backslash. This means writing a double backslash ( \\ ).

Conclusion

Today you learned how to quote a string in Python.

Thanks for reading. I hope you enjoy it!

Источник

Оцените статью