Skip to main content

Python String Tutorial

In this tutorial, you'll learn all about Python Strings: slicing and striding, manipulating and formatting them with the Formatter class, f-strings, templates and more!
· 10 min read

Explore with AI

String is a collection of alphabets, words or other characters. It is one of the primitive data structures and are the building blocks for data manipulation. Python has a built-in string class named str. Python strings are "immutable" which means they cannot be changed after they are created. For string manipulation, we create new strings as we go to represent computed values because of their immutable property.

In this tutorial, you will see strings in depth and will cover the following topics:

string python tutorial

If you're interested to learn more about data structures in Python, surely check out DataCamp's two-part Python Data Science Toolbox. This course dives deeper into functions, iterators, lists, etc.

Strings

You can handle textual data in Python using the str object. Strings are immutable sequences of unicode. Unicode is a system designed to represent all characters from languages. In unicode, each letter, character is represented as a 4-byte number. Each number represents a unique character.

To represent a string, you wrap it within quotes. There can be multiple ways of doing this:

  • Single quotes, just like in this example: 'Single quote allow you to embed "double" quotes in your string.'
  • Double quotes. For example: "Double quote allow you to embed 'single' quotes in your string."
  • Triple quotes, as in this example: """Triple quotes using double quotes""", '''Triple quotes using single quotes.'''

Triple quoted string let you work with multiple line strings, and all associated whitespace will be included in the string.

single_quote = 'Single quote allow you to embed "double" quotes in your string.'
double_quote = "Double quote allow you to embed 'single' quotes in your string."
triple_quote = """Triple quotes allows to embed "double quotes" as well as 'single quotes' in your string. 
And can also span across multiple lines."""

Strings are immutable which means if you try to change any value in a string, it will throw an error. You must create a new string inorder to incorporate the changes.

triple_quote = '''This is triple quoted string using "single" quotes.'''
triple_quote[35] = "'"
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-207-62d335428dcf> in <module>()
      1 triple_quote = '''This is triple quoted string using "single" quotes.'''
----> 2 triple_quote[35] = "'"


TypeError: 'str' object does not support item assignment