Strings

Let’s learn about the string data type and different methods to manipulate strings in Python.

Strings are one of the most popular and useful data types in Python. A string can be created by enclosing characters in either single quotes (' ') or double quotes (" "). Python treats single and double quotes the same. Strings are used to record text information (for example, a person’s name) as well as an arbitrary collection of bytes (for example, the contents of an image file).

Press + to interact
# creating single quotes string
string_example = 'creating single quotes string'
# creating double quotes string
string_example_2 = "creating double quotes string"
# we have lots of other quotes, let's wrap them in double quotes
string_example_3 = "we have lots of other quotes, let's wrap them in double quotes"
print(string_example)
print(string_example_2)
print(string_example_3)
  • A string is a sequence (a positionally ordered collection) of other objects or elements.
  • A string maintains a left-to-right order among the contained items.
  • Items in a string are stored and fetched by their relative positions.
  • Strings are immutable in Python. This means they cannot be changed in place after they are created. In other words, immutable objects can never be overwritten. We can’t change a string by assigning it to one of its positions, but we can always build a new string and assign it to the same name.

Format

Let’s now look at the handy, built-in method format() with an example. Let’s say we have two variables, defined as name = ’James’ ...