Python Strings: Manipulation, Formatting, and Methods

Introduction

Strings are an essential data type in Python. A string is a sequence of characters that can be letters, numbers, symbols, or spaces, such as “hello” or “world”. An important aspect of Python strings is their immutability. This means that once a string is created, its content cannot be directly modified. If you need to make changes, you’ll essentially be creating a new string object.

However, you can generate a new string by concatenating or slicing strings that already exist. In this article, we’ll explore some of the basics of working with strings in Python.

Creating Strings

Strings are created by enclosing characters within either single quotes (‘ ‘), double quotes (” “), or triple quotes (”’ or “””). Triple quotes are useful for multi-line strings or incorporating quotes within the string itself. For example:

name = 'Subhankar'
age = "25"
quote = '''"To be, or not to be,"'''

In the first line, we create a string variable ‘name‘ with the value ‘Subhankar’. In the second line, we create a string variable ‘age’ with the value “25”. Note that even though the value looks like a number, it is still a string because it is enclosed in quotes.

In the third line, we create a string variable ‘quote‘ with the value: ”'”To be, or not to be,””’. We use triple quotes to enclose the string so that we can include both single and double quotes inside the string.

Accessing Characters in a String

Indexing is a technique that allows you to retrieve specific characters in a string. In Python, the initial character in a string has an index of 0. You can access a specific character of a string using the square bracket notation.

my_string = 'Hello, World!'
print(my_string[0])    # Output: H
print(my_string[-1])   # Output: !

In the above example, we have created a string named ‘my_string‘ and printed the first and last characters using indexing. We can also access characters from the end of the string by using negative indexing. In this case, the last character has an index of -1, and the second last character has an index of -2, and so on.

Slicing a String

You can extract a portion of a string using slicing. Slicing allows you to specify a start index, an end index, and a step size. To slice a string, use the following syntax:

string[start:end:step]

In the above syntax, the start parameter specifies the index of the first character you want to include in the substring, the end parameter specifies the index of the first character not to be included in the substring, and the step parameter specifies the increment between each character to include.

my_string = 'Hello, World!'
print(my_string[0:5])   # Output: Hello
print(my_string[7:])    # Output: World!
print(my_string[::2])   # Output: Hlo ol!
print(my_string[1:14:2]) # Output: el,Wrd

In the above example, we have sliced the string ‘my_string‘ using different parameters. The first slice includes the characters from index 0 to index 4. The second slice includes the characters from index 7 to the end of the string. The third slice includes every second character in the string.

In the last print statement, we slice the string ‘my_string‘ from index 1 up to but not including index 14, skipping every second character. The result is the string ‘el,Wrd‘.

String Concatenation

You can concatenate strings using the ‘+‘ operator. For example:

greeting = 'Hello'
name = 'Python'
message = greeting + ', ' + name + '!'
print(message)   # Output: 'Hello, Python!'

In this example, we concatenate the strings ‘Hello’, ‘, ‘, ‘Alice’, and ‘!’ using the ‘+’ operator. The result is the string ‘Hello, Python!’.

String Formatting

String formatting allows you to insert values into a string. There are several ways to format a string in Python, but one common way is to use the ‘format()‘ method. For example:

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

In this example, we use the ‘format()’ method to insert the values of the variables’ name and age into the string ‘My name is {} and I am {} years old.’.

String Methods

Python provides a rich set of built-in string methods that can be used to manipulate and process strings. These methods are functions that are built into the string object and can be accessed using the dot notation.

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

lower()‘ and ‘upper()‘: These methods are used to convert a string to lowercase or uppercase letters, respectively.

my_string = 'Hello, World!'
print(my_string.lower())   # Output: hello, world!
print(my_string.upper())   # Output: HELLO, WORLD!

strip()‘: This method removes any leading or trailing white space characters from a string.

my_string = '   Hello, World!   '
print(my_string.strip())   # Output: 'Hello, World!'

lstrip()‘ and ‘rstrip()‘: These methods remove leading and trailing white space characters from a string, respectively.

my_string = '   Hello, World!   '
print(my_string.lstrip() + "****")   # Output: 'Hello, World!   ****'
print(my_string.rstrip() + "****")   # Output: '   Hello, World!****'

split()‘: This method is used to split a string into a list of sub-strings based on a specified delimiter. The default delimiter is white space.

my_string = 'apple, banana, cherry'
print(my_string.split(','))   # Output: ['apple', ' banana', ' cherry']

replace()‘: This method is used to replace a sub-string in a string with another sub-string.

my_string = 'Hello, World!'
print(my_string.replace('Hello', 'Hi'))   # Output: Hi, World!

startswith()‘ and ‘endswith()‘: These methods are used to check if a string starts or ends with a specified sub-string, respectively.

my_string = 'Hello, World!'
print(my_string.startswith('Hello'))   # Output: True
print(my_string.endswith('World!'))    # Output: True

find()‘ and ‘index()‘: These methods are used to search for a sub-string in a string and return its index. The ‘find()’ method returns -1 if the sub-string is not found, while the ‘index()’ method raises an exception.

my_string = 'Hello, World!'
print(my_string.find('World'))   # Output: 7
print(my_string.index('World'))  # Output: 7

join()‘: This method is used to join a list of strings into a single string using a specified delimiter.

my_list = ['apple', 'banana', 'cherry']
delimiter = ', '
print(delimiter.join(my_list))   # Output: 'apple, banana, cherry'

These are just a few examples of built-in string methods in Python. By using these methods, you can perform various string manipulations and transformations, making it easier to work with textual data in your Python programs.

Exercises

Try some exercises for practicing Python strings.

  1. Create a string variable with your name and print it to the console.
  2. Create two string variables and concatenate them into a single string using the ‘+’ operator.
  3. Create a string variable and extract the first three characters using slicing.
  4. Create a string variable and extract the last three characters using slicing.
  5. Create a string variable with a sentence and split it into individual words using the ‘split()’ method.
  6. Create a string variable with a sentence and replace all occurrences of a certain word with another word using the ‘replace()’ method.
  7. Create a string variable with a sentence and convert it to uppercase using the ‘upper()’ method.
  8. Create a string variable with a sentence and remove all white space characters using the ‘replace()’ method.
Share your love
Subhankar Rakshit
Subhankar Rakshit

Hey there! I’m Subhankar Rakshit, the brains behind PySeek. I’m a Post Graduate in Computer Science. PySeek is where I channel my love for Python programming and share it with the world through engaging and informative blogs.

Articles: 194