Strings are sequences of characters enclosed in single, double, or triple quotes. They are one of the most commonly used data types in Python for storing and manipulating text.
Creating Strings
You can create strings using single quotes, double quotes, or triple quotes for multi-line strings.
Explanation of Code:
Single and double quotes can be used interchangeably. Triple quotes are useful for multi-line strings or strings that contain both single and double quotes.
# Single quotes single_quoted_string = 'Hello, World!' # Double quotes double_quoted_string = "Hello, World!" # Triple quotes (multi-line string) triple_quoted_string = """Hello, World!"""
Accessing Characters in a String
You can access individual characters in a string using indexing. Python uses zero-based indexing.
Explanation of Code:
The index 0
accesses the first character, and the index 7
accesses the eighth character in the string.
text = "Hello, World!" print(text[0]) # Output: H print(text[7]) # Output: W
Slicing Strings
You can extract a substring from a string using slicing.
Explanation of Code:
The slice 0:5
extracts characters from index 0
to 4
, and the slice 7:
extracts characters from index 7
to the end of the string.
text = "Hello, World!" print(text[0:5]) # Output: Hello print(text[7:]) # Output: World!
String Methods
Python provides several built-in methods for string manipulation.
1. upper() – Converts all characters to uppercase.
Explanation of Code:
Converts all characters in the string to uppercase.
text = "Hello, World!" print(text.upper()) # Output: HELLO, WORLD!
2. lower() – Converts all characters to lowercase.
Explanation of Code:
Converts all characters in the string to lowercase.
text = "Hello, World!" print(text.lower())
3. strip() – Removes leading and trailing whitespace.
Explanation of Code:
Removes any leading and trailing spaces from the string.
text = " Hello, World! " print(text.strip()) # Output: Hello, World!
4. replace() – Replaces a substring with another substring.
Explanation of Code:
Replaces occurrences of the substring “World” with “Python”.
text = "Hello, World!" print(text.replace("World", "Python")) # Output: Hello, Python!
5. split() – Splits a string into a list of substrings based on a delimiter.
Explanation of Code:
Splits the string at each comma, returning a list of substrings.
text = "Hello, World!" print(text.split(",")) # Output: ['Hello', ' World!']
String Formatting
Python Provides multiple ways to format strings.
1. Using the +
operator:
Explanation of Code:
Concatenates strings using the +
operator and converts the integer age
to a string.
name = "Alice" age = 25 text = "Name: " + name + ", Age: " + str(age) print(text) # Output: Name: Alice, Age: 25
2. Using the format()
method:
Explanation of Code:
Uses the format()
method to insert name
and age
into the string placeholders {}
.
name = "Alice" age = 25 text = "Name: {}, Age: {}".format(name, age) print(text) # Output: Name: Alice, Age: 25
3. Using f-strings (Python 3.6+):
Explanation of Code:
Uses f-strings for inline variable interpolation, making the code more readable.
name = "Alice" age = 25 text = f"Name: {name}, Age: {age}" print(text) # Output: Name: Alice, Age: 25
Python Strings Example Code
Explanation of Code:
This program creates a string and demonstrates various operations such as accessing characters, slicing, using string methods, and formatting strings.
# Create a string text = " Hello, World! " # Accessing characters print("First character:", text[1]) # Slicing print("Substring:", text[1:6]) # String methods print("Uppercase:", text.upper()) print("Lowercase:", text.lower()) print("Strip:", text.strip()) print("Replace:", text.replace("World", "Python")) print("Split:", text.split(",")) # String formatting name = "Alice" age = 25 formatted_text = f"Name: {name}, Age: {age}" print("Formatted String:", formatted_text)