Strings in Python | Accessing, Examples

Strings in Python are a sequence of characters, which consist of one or more letters, numbers, punctuation marks, and spaces.

For example, “Python” is a string which contains a sequence of six characters ‘P’, ‘y’, ‘t’, ‘h’, ‘o’ and ‘n’.

String is one of the most popular and useful data types in Python. Therefore, Python provides lots of features and functions for it.

In Python, strings are immutable objects of the built-in str class, which store the sequence of characters, called string.

To create strings or a string literal in Python, we must enclose it in either single (‘), double (“) or triple (”’ or “””) quotes and assign it to a variable. The general syntax to create or initialize a string is as:

<name of string> = "<value of string>"

For example:

# Create a string using double quotes.
language = "Python" # Here, language is the name of variable of string type.

Here, we have created a string variable named language and assigned it with a value “Python” in double quotes. Since a string is an array of characters, whenever we store a string into a variable, the first characters always get placed at index number 0.

Look at the below figure to understand better where the first letter of ‘Python’ string has placed at index number 0, second at index number 1, and so on.

Representation of Python strings

From the above figure, it is clear that a string is a sequence or collection of characters stored sequentially. The index number is an integer value. If it is a decimal value, it will raise an error.

Examples of Creating and Storing Strings in Python

Let us see some valid different examples of creating and storing strings in Python.

# Creating strings in single and double quotes.
1. single_quote = 'A string enclosed inside single quotation marks.'
2. double_quote = "A string enclosed inside double quotation marks."

In the above example, we have created two strings in single and double quotation marks and stored them in two variables “single_quote” and “double_quote”, respectively.

We can also create a string of a single character within single quotation marks or double quotation marks. For example:

# Creating a string of a single character in double quotation marks and store it in a variable.
3. single_char_string = "P"

[adinserter block=”5″]
We can also create an empty string within single or double quotation marks. For example:

# Creating empty strings in single and double quotation marks.
4. empty_string = "" 
5. empty_string = '' 

A string that does not contain any character in it, is called empty string. Both 4 and 5 are valid representation of strings, called empty strings.

A string enclosed in single quotation marks can contain double quotation marks and vice versa. For example:

6. single_within_double_quote = "I love 'Python programming'"
7. double_within_single_quote = 'I love "Python coding"'

So, if one type of quotation marks surrounds the string, use another type within it.

Still, you want to use the same quotation marks within a string as you have used to enclose string, you will have to use inner quote with a backslash (/). Let’s understand it with the help of an example.

8. same_quote = 'I don\'t understand love matter' # use backslash before single quote.

In this example, we have used a backslash before single quote within a string. This is called escape. If the string will print on the console, the backslash will not see on the console.

Escape is useful when a string contains a single quote (‘). Python will consider the second single quote as the end of the string. For example:

msg = 'I don't like you'
      SyntaxError: unterminated string literal (detected at line 1)

If you have a string in multiple lines, then create it within triple quotes either using three single quotes or three double quotes. For example:

9. triple_quote_string = """This is a multiline string 
       enclosed within triple quotes. 
       You can use single or double quotation marks 
       depending on your choice."""

[adinserter block=”2″]

10. Let’s write a program in Python to create strings in single, double, and triple quotation marks and display them on the console.

string1 = 'Python is an object-oriented language'
string2 = "It supports graphics programming"
string3 = """It is easy to download and install on a computer."""
print(string1 + '\n' + string2 + '\n' + string3)
      Python is an object-oriented language
      It supports graphics programming
      It is easy to download and install on a computer.

In the above example, we have created three strings with different values. We have used + operator to concatenate three strings and the print() function to print three strings in separate lines using ‘\n’.

Accessing String Characters in Python

In Python, we can access individual characters of a string through index and a range of characters by slicing. An index is a number which denotes the position of elements.

From left to right, the indices start at 0, not 1. So, the first character of a string takes zero as its index number and succeeding characters take 1, 2, 3… and so on as index numbers. Index of the last character is always (length of string – 1).

To access the characters of a string, just write the variable name and enclose the integer number inside the index operator or square brackets [ ]. Let’s take an example in which we will access the characters of a string

Example 1:

# Python program to access the characters of a string literal.
msg = 'Goodbye'
print('String:', msg)
# Access the first character from left of the string.
print('First character of sting:',msg[0])

# Access the second character from left of string.
print('Second character of sting:',msg[1])
# Access the third character of string.
print('Third character of sting:',msg[2])

# Access the last character of string.
print('Last character of sting:',msg[len(msg) - 1])
      String: Goodbye
      First character of sting: G
      Second character of sting: o
      Third character of sting: o
      Last character of sting: e

Indexing also allows negative address references to access the characters of a string from backwards (i.e. from right to left). For example, the last character takes -1 as its index, the second last character takes -2 as its index, and so on.

Let’s take an example based on the taking negative index number for accessing characters of a string.

Example 2:

# Program to access the characters of a string from backwards.
language = 'Python'
# Access the first character of string from back.
print('First character of sting:',language[-1])

# Access the second character of string from back.
print('Second character of sting:',language[-2])
# Access the last character of string from backwards.
print('Last character of sting:',language[-6])
       String: Python
       First character of sting: n
       Second character of sting: o
       Last character of sting: P

Python also consider a space a character. Let’s take an example of it.

Example 3:

# Program to access the space as a character of a string.
greeting = 'Good morning'
# Access the space character of string.
print('Space character of sting:',greeting[4])
      String: Good morning
      Space character of sting: 

If you will access a character which is out of the index range, Python will raise an IndexError error. Python allows only integers to be passed as an index. Float or other types will generate a TypeError.

Example 4:

# Program to access the character of a string out of range.
greeting = 'Good evening'
print('Accessing out of range:',greeting[12])
      IndexError: string index out of range

In this example, we have accessed a character out of index range; it raises an error. So, the index must be within the valid range of a given string, otherwise, an exception will generate resulting an error.

Strings are immutable objects in Python

In Python, strings are immutable objects, meaning once we create it, we can no longer change it. That is, their values cannot be change or modified.

If we try to modify it either by taking a new value, or concatenating another string on the end, etc., Python interpreter will automatically allocate a new space in the memory for a new string object.

So, we cannot perform any changes with the existing string object in Python. This non-changeable behavior is nothing but a string immutability in Python.

Let’s understand it with the help of an example.

Example 5:

# Program to demonstrate that string is an immutable object or data type.
str = 'Python'
print('Original string:',str)
print('Id of original string:',id(str))

str = str + ' Programming'
print('Modified string:',str)
print('Id of modified string:',id(str))
      Original string: Python
      Id of original string: 2466945975984
      Modified string: Python Programming
      Id of modified string: 2466950814480

In the above example program, it looks like we have assigned a string “Python” to a variable str of string type and then appended a string “Programming” to string str.

Thus, the string looks mutable in nature. In fact, it is not happening. When the operation str + “Programming” will be performed, a new string object will create and assign back to str, and deallocate the old string.

In other words, when Python will execute the statement str = str + ” Programming”, it will create a new string object in the memory for storing a new value.

To understand more it clearly, we have used a built-in id() function that returns the identity of an object. Look at the output that the memory address of string object before and after update is different. This shows that we cannot modify or update the value in the existing string object.

Key points of Python Strings

  1. A contiguous set of characters in between single, or double quotation marks is called strings.
  2. Python strings are immutable objects, meaning that we cannot change their values.
  3. There is no character data type in Python.
  4. Single (‘), double (“), or triple (”’ or “””) are used to represent strings in Python.
  5. From the left to right, string indexes begin at 0 and from right to left, it starts at -1.
  6. To access the character of a string, use the variable name and enclose the integer number inside the [ ] operator.

In this tutorial, you have learned about strings in Python with the help of various examples. Hope that you will have understood the basic points of strings and practiced all example programs.
Thanks for reading!!!

⇐ Prev Next ⇒