note.nkmk.me

Create a string in Python (single, double, triple quotes, str())

Posted: 2021-10-06 / Tags: Python, String

In Python, a string (str) is created by enclosing text in single quotes ', double quotes ", and triple quotes (''', """). It is also possible to convert objects of other types to strings with str().

This article describes the following contents.

  • Single quotes: '
  • Double quotes: "
  • Difference between single quotes and double quotes
    • Both values are equal
    • Quotes in strings are handled differently
  • Triple quotes: ''', """
    • Multiple lines
    • Single and double quotes
    • Indentation
  • Convert other types to strings: str()
    • Convert numbers to strings
    • Convert lists and dictionaries to strings
Sponsored Link

Single quotes: '

Enclose text in single quotes ' to make it a string (str).

s = 'abc'
print(s)
# abc

print(type(s))
# <class 'str'>

Double quotes: "

Also, enclose text in double quotes " to make it a string (str).

s = "abc"
print(s)
# abc

print(type(s))
# <class 'str'>

Difference between single quotes and double quotes

Both values are equal

Whether you use single quotes ' or double quotes ", created strings are equal.

s_sq = 'abc'
s_dq = "abc"

print(s_sq == s_dq)
# True

Quotes in strings are handled differently

In a string enclosed in single quotes ', double quotes " can be used as is, but single quotes ' must be escaped with a backslash and written as \'. There is no problem if you write \" for double quotes ".

s_sq = 'a\'b"c'
print(s_sq)
# a'b"c

s_sq = 'a\'b\"c'
print(s_sq)
# a'b"c

In a string enclosed in double quotes ", single quotes ' can be used as is, but double quotes " must be escaped with a backslash and written as \". There is no problem if you write \' for single quotes '.

s_dq = "a'b\"c"
print(s_dq)
# a'b"c

s_dq = "a\'b\"c"
print(s_dq)
# a'b"c

Since it is just a difference in writing, values are equal in both cases.

s_sq = 'a\'b"c'
s_dq = "a'b\"c"

print(s_sq == s_dq)
# True
Sponsored Link

Triple quotes: ''', """

Triple quotes (''', """), that is, three single quotes ' or double quotes ", also make a string (str).

Multiple lines

An error occurs when a newline is inserted in a string enclosed in single or double quotes. To insert a newline, you need to use \n.

# s = 'abc
# xyz'
# SyntaxError: EOL while scanning string literal

s = 'abc\nxyz'
print(s)
# abc
# xyz

Within a string enclosed in triple quotes, line breaks can be written as they are.

s_tq = '''abc
xyz'''

print(s_tq)
# abc
# xyz

print(type(s_tq))
# <class 'str'>

Of course, it does not have to contain line breaks.

s_tq = '''abc'''
print(s_tq)
# abc

Single and double quotes

You can use " in three single quotes ''' and ' in three double quotes """. Values are equal in both cases.

s_tq_sq = '''\'abc\'
"xyz"'''

print(s_tq_sq)
# 'abc'
# "xyz"

s_tq_dq = """'abc'
\"xyz\""""

print(s_tq_dq)
# 'abc'
# "xyz"

print(s_tq_sq == s_tq_dq)
# True

Indentation

If spaces are inserted at the beginning of a line in an attempt to match the indentation, created string includes spaces.

s_tq = '''abc
          xyz'''

print(s_tq)
# abc
#           xyz

There is a way to write the following using line feed and parentheses.

s_multi = ('abc\n'
           'xyz')

print(s_multi)
# abc
# xyz

See the following article for details.

Convert other types to strings: str()

You can use str() to convert objects of other types to strings (str).

str() returns the result of the __str()__ method of the target object. If its type has no __str()__ method defined, it returns the result of repr().

The following are some examples of typical types.

Convert numbers to strings

Integers int and floating point numbers float can be converted to strings str with str().

i = 100

s_i = str(i)
print(s_i)
# 100

print(type(s_i))
# <class 'str'>

f = 0.123

s_f = str(f)
print(s_f)
# 0.123

print(type(s_f))
# <class 'str'>

For example, int can be written in hexadecimal, float in exponential, and so on, but when converted to a string with str(), they are converted to standard decimal strings.

i = 0xFF
print(i)
# 255

s_i = str(i)
print(s_i)
# 255

f = 1.23e+10
print(f)
# 12300000000.0

s_f = str(f)
print(s_f)
# 12300000000.0

Use the built-in function format() to convert it to a string of a desired format.

s_i_format = format(i, '#X')
print(s_i_format)
# 0XFF

s_f_format = format(f, '.2e')
print(s_f_format)
# 1.23e+10

If you want to convert a string of numbers to numeric values, see the following article.

Convert lists and dictionaries to strings

Lists list and dictionaries dict can also be converted to strings str with str().

l = [0, 1, 2]

s_l = str(l)
print(s_l)
# [0, 1, 2]

print(type(s_l))
# <class 'str'>

d = {'a': 1,
     'b': 2,
     'c': 3}

s_d = str(d)

print(s_d)
# {'a': 1, 'b': 2, 'c': 3}

print(type(s_d))

You can use pformat() of the pprint module of the standard library to convert it to a well-formed string.

import pprint

dl = {'a': 1, 'b': 2, 'c': [100, 200, 300]}

s_dl = str(dl)
print(s_dl)
# {'a': 1, 'b': 2, 'c': [100, 200, 300]}

p_dl = pprint.pformat(dl, width=10)
print(p_dl)
# {'a': 1,
#  'b': 2,
#  'c': [100,
#        200,
#        300]}

print(type(p_dl))
# <class 'str'>

For more information about pprint, see the following article.

Sponsored Link
Share

Related Categories

Related Articles