Python Tutorials · Python Strings

Python Strings

Learn all about Python Strings in this comprehensive tutorial.

5 min read beginner
  • 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:

python

Quotes Inside Quotes

You can use quotes inside a string, as long as they don't match the quotes surrounding the string:

python

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:

python

Multiline Strings

You can assign a multiline string to a variable by using three quotes:

python

Or three single quotes:

python
Note: Note: in the result, the line breaks are inserted at the same position as in the code.

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.

python

Looping Through a String

Since strings are arrays, we can loop through the characters in a string, with a for loop.

python

Learn more about For Loops in our Python For Loops chapter.

String Length

To get the length of a string, use the len() function.

python

Check String

To check if a certain phrase or character is present in a string, we can use the keyword in.

python

Use it in an if statement:

python

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.

python

Use it in an if statement:

python

Module quiz

2 questions
1

Which of the following is true about Python Strings?

2

What is the most common pitfall when working with Python Strings?

Answer all questions to submit.