Strings

A string is a sequence of characters (letters, numbers, whitespace or punctuation) enclosed by quotation marks. It can be enclosed using either the double quotation mark " or the single quotation mark '.

Multi-line Strings

If a string has to be broken into multiple lines, the backslash character \ can be used to indicate that the string continues on the next line.

longer = "This string is broken up \
over multiple lines"

An alternative is to use three quote-marks (""" or ''') instead of one. This method is useful if the string being defined contains a lot of quotation marks and we want to be sure we don’t close it prematurely.

leaves_of_grass = """
Poets to come! orators, singers, musicians to come!
Not to-day is to justify me and answer what I am for,
But you, a new brood, native, athletic, continental, greater than
  before known,
Arouse! for you must justify me.
"""

Concatenation

The + operator doesn’t just add two numbers, it can also “add” two strings! The process of combining two strings is called string concatenation. Performing string concatenation creates a brand new string comprised of the first string’s contents followed by the second string’s contents (without any added space in-between).

greeting_text = "Hey there!"
question_text = "How are you doing?"

full_text = greeting_text + question_text
# Prints "Hey there!How are you doing?"
print(full_text)

full_text = greeting_text + " " + question_text
# Prints "Hey there! How are you doing?"
print(full_text)

If you want to concatenate a string with a number you will need to make the number a string first, using the str() function. If you’re trying to print() a numeric variable you can use commas to pass it as a different argument rather than converting it to a string.

Using str() we can convert variables that are not strings to strings and then concatenate them. But we don’t need to convert a number to a string for it to be an argument to a print statement.

Joining strings with delimiter

Last updated