String & Subtring in Python

In Python, a string is a sequence of characters, such as letters, numbers, symbols, and spaces, enclosed within either single quotes (' ') or double quotes (" "). Strings are immutable, meaning their contents cannot be changed after they are created. They support various operations and methods for manipulation and access.

A substring in Python refers to a smaller sequence of characters that exists within a larger string. It's a part of the original string. You can extract substrings using slicing or various string manipulation methods available in Python.

String Subset

To check if a string is a subset of another string, you can use the in keyword or the issubset() method, depending on the context of what you mean by "subset."

Checking if one string is a subset of another:

  • Using the in keyword:
string1 = "hello world"
string2 = "hello"

if string2 in string1:
    print("string2 is a subset of string1")
else:
    print("string2 is not a subset of string1")
  • Using the issubset() method (for sets):
string1 = "hello world"
string2 = "hello"

# Convert strings to sets to use issubset() method
subset_check = set(string2).issubset(set(string1))

if subset_check:
    print("string2 is a subset of string1")
else:
    print("string2 is not a subset of string1")

String Indeces

Strings are sequences of characters, and you can access individual characters within a string using string indices. String indexing allows you to retrieve specific characters from a string based on their position (index) within the string.

String indices in Python are zero-based, meaning the first character of a string has an index of 0, the second character has an index of 1, and so on.

Here's a brief example of string indexing in Python:

my_string = "Hello, World!"

# Accessing individual characters using positive indices
print(my_string[0])   # Output: 'H'

# Accessing characters using negative indices (counting from the end of the string)
print(my_string[-1])  # Output: '!'
  • Positive indices refer to positions starting from the beginning of the string (from left to right), where my_string[0] represents the first character and so forth.
  • Negative indices, such as my_string[-1], represent positions counting from the end of the string (from right to left). -1 refers to the last character in the string, -2 refers to the second-to-last character, and so on.

It's important to note that attempting to access an index that doesn't exist within the string will result in an IndexError. Also, strings in Python are immutable, so you cannot directly change the characters of a string using indices.

String Replacement

In Python, you can replace parts of a string with other substrings using the replace() method or by slicing and concatenating strings together. Here's how you can perform string replacement in Python:

  • Using replace() method:

The replace() method replaces all occurrences of a specified substring with another substring within a string.

original_string = "Hello, World!"
new_string = original_string.replace("Hello", "Hi")  # Replace "Hello" with "Hi"

print(new_string)  # Output: 'Hi, World!'
  • Using string slicing and concatenation:

You can also perform string replacement by slicing the original string and concatenating the parts you want to keep with the new substring.

original_string = "Hello, World!"
replacement = "Hi"
substring_to_replace = "Hello"

new_string = replacement + original_string[len(substring_to_replace):]

print(new_string)  # Output: 'Hi, World!'

Splitting a String in Python

In Python, the split() method is used to split a string into a list of substrings based on a specified delimiter. The delimiter can be a space, comma, tab, or any other character you choose. By default, the split() method uses whitespace as the delimiter if no separator is specified.

Here's an example demonstrating how to use the split() method:

  • Splitting a string using whitespace as a delimiter:
my_string = "Hello, World! This is a sample string."
words = my_string.split()  # Split the string into words using whitespace as the delimiter

print(words)
# Output: ['Hello,', 'World!', 'This', 'is', 'a', 'sample', 'string.']
  • Splitting a string using a specific delimiter:
my_string = "apple,banana,orange,grape"
fruits = my_string.split(",")  # Split the string using comma as the delimiter

print(fruits)
# Output: ['apple', 'banana', 'orange', 'grape']

In the first example, split() without any argument splits the string based on whitespace (spaces, tabs, newlines, etc.) and returns a list of words.

In the second example, split(",") uses a comma as the delimiter to split the string into substrings based on the occurrence of commas.

You can also specify the maximum number of splits using an additional argument in the split() method. For instance, split(',', 2) will perform a maximum of 2 splits based on the comma delimiter.

Append to a String

Strings are immutable, which means that once a string is created, you cannot directly append or modify its contents. However, you can create a new string by concatenating existing strings or adding new substrings to it.

You can use the + operator or the += augmented assignment operator to append or concatenate strings together:

  • Using concatenation:
original_string = "Hello, "
appended_string = original_string + "World!"
print(appended_string)
# Output: 'Hello, World!'
  • Using the += operator:
original_string = "Hello, "
original_string += "World!"
print(original_string)
# Output: 'Hello, World!'

Both of these methods create a new string by combining the contents of the original string with the string you want to append. It's important to note that these methods don't directly modify the original string but create a new string containing the concatenated values.

If you need to append multiple strings in a loop or over a collection of strings, you can use the join() method:

  • Using join() to concatenate multiple strings efficiently:
strings_to_append = ["Hello", ", ", "World", "!"]
appended_string = "".join(strings_to_append)
print(appended_string)
# Output: 'Hello, World!'

String Interpolation

String interpolation refers to the process of inserting values of variables or expressions into a string. In Python, there are multiple ways to perform string interpolation:

1.Using f-strings (Formatted string literals, Python 3.6+) :

f-strings provide a concise and readable way to embed expressions inside strings. You can directly insert variables and expressions into strings by prefixing the string with f or F and using curly braces to enclose the variable or expression.

Example:

name = "Alice"
age = 30
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)
# Output: 'My name is Alice and I am 30 years old.'

2. Using .format() method :

The .format() method allows inserting values into a string using placeholders which are replaced by the values passed to the format() method.

Example:

name = "Bob"
age = 25
formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string)
# Output: 'My name is Bob and I am 25 years old.'

3. Using % operator (Older method, still valid) :

The % operator can be used for string interpolation by using format specifiers like %s for strings, %d for integers, %f for floats, etc.

Example:

name = "Charlie"
age = 28
formatted_string = "My name is %s and I am %d years old." % (name, age)
print(formatted_string)
# Output: 'My name is Charlie and I am 28 years old.'

f-strings are the most preferred and modern way of performing string interpolation in Python due to their readability, simplicity, and flexibility in embedding variables and expressions directly into strings.

How to Reverse a String

In Python, you can reverse a string using different methods. Here are a few common approaches.

Using String Slicing:

One of the simplest ways to reverse a string in Python is by using string slicing. You can slice the string with a step size of -1, which will reverse the string.

Example:

my_string = "Hello, World!"
reversed_string = my_string[::-1]
print(reversed_string)
# Output: '!dlroW ,olleH'

Using the reversed() function:

The reversed() function can reverse any iterable, including strings. You'll need to convert the reversed iterable back to a string using the join() method.

Example:

my_string = "Hello, World!"
reversed_string = ''.join(reversed(my_string))
print(reversed_string)
# Output: '!dlroW ,olleH'

Using a Loop:

You can also reverse a string by iterating through it in reverse order and building the reversed string character by character.

Example:

my_string = "Hello, World!"
reversed_string = ''
for char in my_string:
    reversed_string = char + reversed_string
print(reversed_string)
# Output: '!dlroW ,olleH'

Does a String Contain a Substring

In Python, to check if a string contains a specific substring, you can use the in keyword or the find() method. These methods help determine whether a substring is present within a string.

  • Using the in keyword:

The in keyword checks if a substring exists within a string.

Example:

my_string = "Hello, World!"

if "Hello" in my_string:
    print("Substring 'Hello' found")
else:
    print("Substring 'Hello' not found")
# Output: Substring 'Hello' found
  • Using the find() method:

The find() method returns the lowest index of the substring if found in the string. If the substring is not found, it returns -1.

Example:

my_string = "Hello, World!"

index = my_string.find("World")

if index != -1:
    print(f"Substring 'World' found at index {index}")
else:
    print("Substring 'World' not found")
# Output: Substring 'World' found at index 7

Length of a String

You can find the length of a string—the number of characters in a string—using the len() function. It returns the length of the given string.

Here's an example:

my_string = "Hello, World!"
length = len(my_string)

print(f"The length of the string is: {length}")
# Output: The length of the string is: 13

A List to a String Conversion in Python

In Python, you can convert a list of strings into a single string using various methods. One common approach is to use the join() method or string formatting.

  • Using the join() method:

The join() method is applied to a separator string and takes a list of strings as an argument. It concatenates the strings in the list, placing the separator between each element, resulting in a single string.

Example:

my_list = ['This', 'is', 'a', 'list', 'of', 'words']
separator = ' '  # Define the separator (in this case, a space)

result_string = separator.join(my_list)
print(result_string)
# Output: 'This is a list of words'
  • Using string formatting:

You can also use string formatting to join the elements of a list.

Example:

my_list = ['This', 'is', 'a', 'list', 'of', 'words']

result_string = ' '.join(['{}'.format(word) for word in my_list])
print(result_string)
# Output: 'This is a list of words'
Profile picture for user Sarah Chen

The only author and editor of all pages on the site. Most of what I write about is based on years of book reading on the topic.

Updated: 15 March 2024