Tutorial

Strings in Python

8 min read

In Python, strings are one of the fundamental data types, and they consist of a sequence of characters enclosed in either single or double quotes. This makes strings an essential component of programming in Python.

Strings play a crucial role in many applications, as they are used to represent textual data such as names, addresses, messages, descriptions, etc.

Strings in Python are not a data type but also objects that come with a rich set of built-in methods and operations that can be used to manipulate and transform them.

In this tutorial, we will learn the basics of strings in Python, including how to –

  • create
  • access
  • modify, and manipulate

Strings using various methods and operators in Python.

We will also learn some advanced string operations such as –

  • formatting
  • slicing and searching

These are essential for working with strings in real-world scenarios.

Types of Strings in Python

There are different types of strings in Python that can be used depending on the specific use case.

Here are some of the most commonly used types of Python strings:

  • Single-quoted strings: Single-quoted strings are created by enclosing the text within a pair of single quotes (‘ ‘). They are the most basic type of strings in Python and are commonly used to represent short text messages.
  • Double-quoted strings: Double-quoted strings are created by enclosing the text within a pair of double quotes (” “). Like single-quoted strings, they are used to represent short text messages, but they also allow you to include single quotes within the text.
  • Triple-quoted strings: Triple-quoted strings are created by enclosing the text within a pair of triple quotes (“”” “””). They are used to represent longer text messages, such as paragraphs or docstrings, and allow you to include line breaks and special characters within the text.
  • Raw strings: Raw strings are created by prefixing a string with the letter ‘r‘. They are used to represent regular expressions or file paths, as they treat backslashes as literal characters and ignore escape sequences.

Example of Python String:

pattern = r'\d{3}-\d{2}-\d{4}'  # represents a social security number pattern
path = r'C:\Users\username\Documents\file.txt'  # represents a file path on Windows

Accessing Strings in Python

Accessing Characters: To access a specific character in a string, we can use the indexing operator, which is represented by square brackets [] and takes an integer index as an argument. The index starts from 0 for the first character and goes up to n-1 for the nth character, where n is the length of the string.

Example:

message = 'Hello, world!'
print(message[0])  # Output: H
print(message[7])  # Output: w
print(message[-1]) # Output: !

Note: We can also use negative indexing to access characters from the end of the string, where -1 refers to the last character, -2 refers to the second-last character, and so on.

Modifying Strings in Python

Modifying Characters: Strings are immutable in Python, which means that we cannot modify a string in place.

However, we can create a new string by slicing and concatenating the original string with the desired modification.

To modify a specific character in a string, we can use slicing to create two substrings, and then concatenate them with the desired character in between.

Example of modifying string in Python:

message = 'Hello, world!'
new_message = message[:7] + 'W' + message[8:]
print(new_message)  # Output: Hello, World!

Here, we used slicing to create two substrings: message[:7] returns ‘Hello, ‘ and message[8:] returns ‘orld!‘. Then, we concatenated them with the uppercase ‘W‘ in between to create a new string ‘Hello, World!‘.

Why are Python Strings Immutable?

In Python, strings are immutable, which means that once a string is created, its contents cannot be changed.

There are several reasons why strings are immutable in Python:

  • Memory Efficiency: Immutable objects are more memory-efficient than mutable objects because they can be stored in a fixed amount of memory. In Python, each string is stored as a sequence of Unicode characters, and once the string is created, its length and contents remain fixed. This means that the interpreter can allocate a fixed amount of memory for the string and reuse it whenever the string is referenced or copied, without worrying about any changes in the contents.
  • Thread Safety: Immutable objects are inherently thread-safe because they cannot be modified by multiple threads simultaneously. In Python, when multiple threads access the same string object, they are guaranteed to see the same contents without the risk of a race condition or inconsistent state.
  • Hashability: Immutable objects can be used as dictionary keys or set elements because they have a fixed and unchanging hash value. In Python, when an object is used as a dictionary key or set element, its hash value is used to identify its position in the hash table. Since the hash value of a string is based on its contents and length, an immutable string can be used as a reliable and efficient key or element.
  • Security: Immutable objects are more secure than mutable objects because they cannot be modified after they are created. In Python, if a string is used to store sensitive data such as passwords or cryptographic keys, its immutability ensures that the data cannot be accidentally or intentionally altered by a malicious user.

String Operation in Python

In Python, there are several built-in operations that we can perform on strings to manipulate them and extract useful information.

Here are some of the most commonly used string operations in Python:

  • Concatenation: We can concatenate two or more strings using the + operator or the += operator. This operation creates a new string that contains the contents of both strings.

Example of concatenation in Python :

name = 'John'
greeting = 'Hello, ' + name
print(greeting)  # Output: Hello, John

message = 'Hello, '
message += 'world!'
print(message)  # Output: Hello, world!
  • Repetition: We can repeat a string multiple times using the * operator. This operation creates a new string that contains multiple copies of the original string.

Example of repetition in Python:

pattern = '*' * 10
print(pattern)  # Output: **********
  • Slicing: We can extract a portion of a string using slicing, which is done using the colon (:) operator. This operation creates a new string that contains the characters from the original string within the specified range.

Example of Slicing in Python:

message = 'Hello, world!'
substring = message[0:5]
print(substring)  # Output: Hello
  • Length: You can determine the length of a string using the len() function. This operation returns an integer that represents the number of characters in the string.

Example of length in Python:

message = 'Hello, world!'
length = len(message)
print(length)  # Output: 13
  • Searching: We can search for a substring within a string using the in operator or the find() method. The in operator returns a boolean value indicating whether the substring is present in the string, while the find() method returns the index of the first occurrence of the substring, or -1 if it is not found.

Example of searching in Python:

message = 'Hello, world!'
print('world' in message)  # Output: True

index = message.find('world')
print(index)  # Output: 7

Python provides a rich set of operations for manipulating and extracting information from strings. Understanding these operations is essential for working with textual data effectively and efficiently.

Different Methods in Python Strings

In Python, strings are objects that have a variety of built-in methods that can be used to manipulate and analyze the contents of a string. Here are some of the most commonly used string methods in Python:

  1. strip(): This method removes whitespace characters (spaces, tabs, newlines) from the beginning and end of a string.
  2. lower() and upper(): These methods convert a string to lowercase or uppercase, respectively.
  3. replace(): This method replaces all occurrences of a specified substring with another substring.
  4. split(): This method splits a string into a list of substrings based on a delimiter. By default, the delimiter is a space character.
  5. join(): This method joins a list of substrings into a single string, using a specified delimiter.
  6. find(): This method searches for a specified substring within a string and returns the index of the first occurrence, or -1 if the substring is not found.
  7. count(): This method counts the number of occurrences of a specified substring within a string.

f Strings in Python 3

f-strings (formatted string literals) are a powerful feature of Python 3 that allows us to embed expressions inside string literals, using curly braces {} to enclose the expressions.

F-strings are useful for constructing dynamic strings that depend on variables or other runtime information.

Example of Python f string:

name = 'John'
age = 25
message = f'My name is {name} and I am {age} years old.'
print(message)  # Output: 'My name is John and I am 25 years old.'

Here, the f-string contains two expressions: {name} and {age}. These expressions are replaced with the values of the corresponding variables at runtime.

F-strings can also include expressions that are more complex, such as arithmetic operations, function calls, and conditional expressions. Here are some examples:

a = 10
b = 20
c = f'The sum of {a} and {b} is {a + b}.'
print(c)  # Output: 'The sum of 10 and 20 is 30.'

def greet(name):
    return f'Hello, {name}!'

d = greet('John')
print(d)  # Output: 'Hello, John!'

is_valid = True
e = f'The value is {"valid" if is_valid else "invalid"}.'
print(e)  # Output: 'The value is valid.'

Conclusion

Strings are an essential part of any programming language, and Python is no exception.

Python strings are sequences of characters, and they are widely used for storing and manipulating textual data.

Python provides many built-in methods and functions that can be used to manipulate strings in various ways, such as converting them to uppercase or lowercase, splitting them into substrings, and searching for specific patterns. In addition,

Python’s f-strings feature allows for easy formatting of dynamic strings, making it easy to include variables and expressions inside string literals. With the combination of Python’s built-in string methods and f-strings, working with textual data in Python is simple and efficient.

Get an online python tutor and improve your Python programming skills.