A string is a sequence of characters contained within a pair of single quotes (
') or double quotes(
"). Strings can store words, sentences, or whole paragraphs. They can be any length and can contain letters, numbers, symbols, and spaces.
message1 = "I am a string"message2 = 'I am also a string'
Other data types such as
booleans can also be
strings if they are wrapped in quotes.
|“2” (with double-quotes)||Yes ✅|
|‘3.6’ (with single-quotes)||Yes ✅|
|“True” (also in quotes)||Yes ✅|
|7 (integer)||No ❌|
|Hello (no quotes)||No ❌|
|True (boolean)||No ❌|
Strings are immutable; they cannot change. Every time an operation is performed on a string, a new string is created in memory.
Accessing the Characters of a String
Strings in Python are technically a type of list — one in which each character is a separate element. This means each character in a string can be individually accessed by index, like with the elements in a list:
myString = "Hello, World!"var_1 = myStringvar_2 = myString[7:]var_3 = myString[1:4]print("var_1: " + var_1) # Output: var_1: Hprint("var_2: " + var_2) # Output: var_2: World!print("var_3: " + var_3) # Output: var_3: ell
If an attempt is made to access an index out of bounds, it will return an
name = "phillis"name # Throws an IndexError
Strings can be long or short. For longer text, a multi-line string can be used. Multi-line strings begin and end with three single or double quotes:
my_string = """If it were done when 'tis done, then 'twere wellIt were done quickly: if the assassinationCould trammel up the consequence, and catchWith his surcease success; that but this blowMight be the be-all and the end-all here,But here, upon this bank and shoal of time,We'ld jump the life to come."""
Sometimes a string may have a character that Python tries to interpret, such as
my_string = 'It's a lovely day!'print(my_string)
This will raise an error, because the interpreter thinks the second
' marks the end of the string.
File "main.py", line 1my_string = 'It's a lovely day!'^SyntaxError: invalid syntax
These characters can be “escaped” by adding a backslash beforehand. The
\ is called an escape character.
The backslash will not be visible if the string is printed:
my_string = 'It\'s a lovely day!'print(my_string)# Output: It's a lovely day!
This problem can be avoided by wrapping strings containing
' characters in double quotes:
my_string = "It's a lovely day!"print(my_string)# Output: It's a lovely day!
Python also has a series of non-printing characters that can modify strings. For example,
\n adds a new line and
\t adds a tab:
note = "I am on top!\nI am on bottom. \n\tI am indented!"print(note)
This will output:
I am on top!I am on bottom.I am indented!
Python has special operators to modify strings. For example,
+ can be used to concatenate strings, and
* can be used to multiply a string. The keyword
in can be used to see if a given character or substring exists in a
string_one = "Hello, "string_two = "World! "combo = string_one + string_twoprint(combo)# Output: Hello, World!new_combo = combo * 2print(new_combo)# Output: Hello, World! Hello, World!if "World" in new_combo:print("It's here!")# Output: It's here!
Strings can also be formatted with either of the following:
f/Fflag (placed before the opening quotation mark).
- The .format() method (requires manually adding placeholders).
Python can use comparison operators to compare the contents of two strings. The operators behave as they do with numeric arguments:
||Less than or equal to||Returns
||Greater than or equal to||Returns
The following example demonstrates string comparison:
Built-in String Methods
Python has a number of built-in string methods that manipulate strings. However, when these methods are called, the original string will not be changed, so any modifications will need to be saved to a new variable. A few useful built-in string methods are listed below.
- Takes in a string, and returns a copy of the string in Capital Case.
- Returns a copy of the string with all characters in lowercase.
- Finds the number of times the specified substring occurs within a given string.
- Checks whether or not a string ends with a given value.
- Takes in a substring (and optionally start/end index), return the index number of the first occurrence of the substring inside a string.
- Returns a string with values inserted via placeholders.
- Searches through a string variable for the occurrence of a pattern or a substring.
- Takes in a string and returns True if all the letters in the string are in lowercase, else returns False. Ignores spaces, newlines, numeric and special characters in the string.
- Takes in a string and returns True if all the letters in the string are in uppercase, else returns False. Ignores spaces, newlines, numeric and special characters in the string.
- Concatenates all items from an iterable into a single string.
- Takes a string, and returns a copy of that string in which all letters are lowercase. Numbers and symbols are not changed.
- Searches a string for a given keyword and splits that string into a three part tuple.
- Replace a specific substring with another substring.
- Converts a string to a list. It takes a specified delimiter and a maximum number of items to split as optional parameters.
- Checks whether or not a string starts with a given value.
- Takes a string and returns a copy of that string in which all lowercase letters are uppercase, and all upercase letters are lowercase. Numbers and symbols are not changed.
- Takes in a string and returns a copy of the string formatted in the title case: each word in the string is capitalized.
- Takes a string, and returns a copy of that string in which all letters are uppercase. Numbers and symbols are not changed.
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.