Home » Learn Python » Getting Started » Python Strings

Python Strings

In programming, a “string” means a sequence of characters; in other words, some text.

Short pieces of text in Python are defined by enclosing them in double or single quotes (it doesn’t matter which; there’s no difference). We can then assign the text to a variable, so we can refer to it later.

text1 = "This is some text"
print(text1)

text2 = 'This is also some text.'
print(text2)
This is some text
This is also some text.

Multi-line Strings

Double or single quotes only work for a single line of text. If we want to create a multi-line string, we can use triple quotes.

some_text = """
This is a multi-line block of text.
We're assigning it to the variable 'some text'
Then we'll print it. 
"""

print(some_text)
This is a multi-line block of text.
We're assigning it to the variable 'some text'
Then we'll print it. 

Multi-line Comments

Python doesn’t have any special syntax for multi-line comments, but you can simply use a multi-line string. If you don’t assign it to a variable or do anything with it, the Python interpreter basically ignores it.

"""
This is effectively a multi-line comment.

We've created a string, but we're not assigning it
to any variable.
"""

# This is a single-line comment

Using Quotes Within Strings

If you’ve used double-quotes as your string delimiter, you can’t then use double quotes within the string itself. This causes a syntax error and you get a traceback in your console.

There are at least two good options for dealing with this problem:

  • You can use single quotes within double quotes or double quotes within single quotes, or either type of quote within triple quotes.
  • Alternatively, you can place a backslash before the quotes within your string. Then they are interpreted as ordinary text.
text1 = "This is 'valid' Python"
text2 = 'This is also "valid" Python'
text3 = "This also \"works\""

print(text1)
print(text2)
print(text3)
This is 'valid' Python
This is also "valid" Python
This also "works"

Leave a Reply

Blog at WordPress.com.

%d