Python String


In this tutorial, we will explore the concept of strings in Python.

A string is a sequence of characters enclosed in either single quotes (' ') or double quotes (" ").

Python treats strings as immutable objects, which means they cannot be modified once created. We will cover various operations and methods available for working with strings in Python.

 

Creating a String


To create a string in Python, you can simply assign a sequence of characters to a variable using quotes. Here are a few examples:

# Using single quotes
my_string1 = 'Hello, World!'

# Using double quotes
my_string2 = "Python is awesome!"

# Combining single and double quotes
my_string3 = 'I love "Python" programming.'


Accessing Characters in a String


Individual characters in a string can be accessed using indexing. The index of the first character is 0, and the index of the last character is len(string) - 1. Here's an example:

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


String Slicing


String slicing allows you to extract a substring from a larger string. It is done by specifying a range of indices.

The syntax for string slicing is string[start:end:step], where start is the starting index, end is the ending index (exclusive), and step is the step size. If any of these values are omitted, they are assumed to be the default values.

Here are a few examples:

my_string = "Hello, World!"
print(my_string[0:5])  # Output: Hello
print(my_string[7:])  # Output: World!
print(my_string[:5])  # Output: Hello
print(my_string[::2])  # Output: HloWrd

 

String Concatenation


String concatenation is the process of joining two or more strings together. In Python, you can use the + operator to concatenate strings. Here's an example:

string1 = "Hello"
string2 = "World"
result = string1 + " " + string2
print(result)  # Output: Hello World


String Methods


Python provides many built-in methods for working with strings. Here are some commonly used string methods:

len(string): Returns the length of the string.
string.lower(): Returns a copy of the string converted to lowercase.
string.upper(): Returns a copy of the string converted to uppercase.
string.strip(): Returns a copy of the string with leading and trailing whitespace removed.
string.split(separator): Splits the string into a list of substrings based on the specified separator.
string.replace(old, new): Returns a copy of the string with all occurrences of old replaced by new.
string.find(substring): Returns the index of the first occurrence of substring in the string, or -1 if not found.


Here's an example that demonstrates the usage of some of these methods:

my_string = "   Hello, World!   "
print(len(my_string))  # Output: 17
print(my_string.lower())  # Output:    hello, world!   
print(my_string.strip())  # Output: Hello, World!
print(my_string.split(','))  # Output: ['   Hello', ' World!   ']
print(my_string.replace('World', 'Python'))  # Output:    Hello, Python!   
print(my_string.find('World'))  # Output: 9


These are just a few examples of the many string methods available in Python. You can explore more string methods in the Python documentation.

 

String Formatting


String formatting allows you to create dynamic strings by embedding variables or expressions within a string. Python provides several ways to format strings:

Using the ‘%’ operator: This is an older formatting method. Here's an example:

name = "Alice"
age = 25
print("My name is %s and I am %d years old." % (name, age))


Using the ‘str.format()’ method: This method provides more flexibility in formatting strings. Here's an example:

name = "Bob"
age = 30
print("My name is {} and I am {} years old.".format(name, age))


Using f-strings (formatted string literals): Introduced in Python 3.6, f-strings provide a concise and readable way to format strings. Here's an example:

name = "Charlie"
age = 35
print(f"My name is {name} and I am {age} years old.")


All three methods achieve the same result: printing the formatted string "My name is <name> and I am <age> years old."

 

Summary


In this chapter, we covered the basics of working with strings in Python. We learned how to create strings, access characters using indexing, perform string slicing, concatenate strings, use string methods, and format strings. Strings are a fundamental data type in Python and are extensively used in many programming tasks. With the knowledge gained from this tutorial, you should be able to manipulate and work with strings effectively in your Python programs.

 

 

© 2022-2023 All rights reserved.