Python Strings
Learn all about Python Strings in this comprehensive tutorial.
- •Strings in python are surrounded by either single quotation marks, or double quotation marks.
- •You can use quotes inside a string, as long as they don't match the quotes surrounding the string:
- •Assigning a string to a variable is done with the variable name followed by an equal sign and the string:
- •You can assign a multiline string to a variable by using three quotes:
- •Like many other popular programming languages, strings in Python are arrays of unicode characters.
- •Since strings are arrays, we can loop through the characters in a string, with a for loop.
- •To get the length of a string, use the len() function.
- •To check if a certain phrase or character is present in a string, we can use the keyword in.
- •To check if a certain phrase or character is NOT present in a string, we can use the keyword not in.
Strings
Strings in python are surrounded by either single quotation marks, or double quotation marks.
'hello' is the same as "hello".
You can display a string literal with the print() function:
Quotes Inside Quotes
You can use quotes inside a string, as long as they don't match the quotes surrounding the string:
Assign String to a Variable
Assigning a string to a variable is done with the variable name followed by an equal sign and the string:
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Or three single quotes:
Strings are Arrays
Like many other popular programming languages, strings in Python are arrays of unicode characters.
However, Python does not have a character data type, a single character is simply a string with a length of 1.
Square brackets can be used to access elements of the string.
Looping Through a String
Since strings are arrays, we can loop through the characters in a string, with a for loop.
Learn more about For Loops in our Python For Loops chapter.
String Length
To get the length of a string, use the len() function.
Check String
To check if a certain phrase or character is present in a string, we can use the keyword in.
Use it in an if statement:
Learn more about If statements in our Python If...Else chapter.
Check if NOT
To check if a certain phrase or character is NOT present in a string, we can use the keyword not in.
Use it in an if statement:
Module quiz
2 questionsWhich of the following is true about Python Strings?
What is the most common pitfall when working with Python Strings?
Answer all questions to submit.