4 - Strings
4 - Strings
Introduction
Strings are one of the most fundamental data types in Python. A string is a
sequence of characters enclosed within either single quotes ( ' ), double quotes
( " ), or triple quotes ( ''' or “““).
Creating Strings
You can create strings in Python using different types of quotes:
# Single-quoted string
a = 'Hello, Python!'
# Double-quoted string
b = "Hello, World!"
String Indexing
Each character in a string has an index:
text = "Python"
print(text[0]) # Output: P
print(text[1]) # Output: y
print(text[-1]) # Output: n (last character)
String Slicing
You can extract parts of a string using slicing:
String Methods
Python provides several built-in methods to manipulate strings:
String Formatting
Python offers multiple ways to format strings:
name = "John"
age = 25
# Using format()
print("My name is {} and I am {} years old.".format(name, age))
Multiline Strings
Triple quotes allow you to create multi-line strings:
message = '''
Hello,
This is a multi-line string example.
Goodbye!
'''
print(message)
Summary
• Strings are sequences of characters.
• Use single, double, or triple quotes to define strings.
• Indexing and slicing allow accessing parts of a string.
• String methods help modify and manipulate strings.
• f-strings provide an efficient way to format strings.
Introduction
In Python, strings are sequences of characters, and each character has an index.
You can access individual characters using indexing and extract substrings using
slicing.
String Indexing
Each character in a string has a unique index, starting from 0 for the first character
and -1 for the last character.
text = "Python"
print(text[0]) # Output: P
print(text[1]) # Output: y
print(text[-1]) # Output: n (last character)
print(text[-2]) # Output: o
String Slicing
Slicing allows you to extract a portion of a string using the syntax
string[start:stop:step] .
Step Parameter
Summary
• Indexing allows accessing individual characters.
• Positive indexing starts from 0, negative indexing starts from -1.
• Slicing helps extract portions of a string.
• The step parameter defines the interval for selection.
• Using [::-1] reverses a string.
Introduction
Python provides a variety of built-in string methods and functions to manipulate
and process strings efficiently.
Changing Case
Removing Whitespace
text = "apple,banana,orange"
fruits = text.split(",")
print(fruits) # Output: ['apple', 'banana', 'orange']
new_text = " - ".join(fruits)
print(new_text) # Output: "apple - banana - orange"
text = "Python123"
print(text.isalpha()) # Output: False
print(text.isdigit()) # Output: False
print(text.isalnum()) # Output: True
print(text.isspace()) # Output: False
print(ord('A')) # Output: 65
print(chr(65)) # Output: 'A'
name = "Alice"
age = 30
print("My name is {} and I am {} years old.".format(name, age))
print(f"My name is {name} and I am {age} years old.")
Summary
Introduction
String formatting is a powerful feature in Python that allows you to insert variables
and expressions into strings in a structured way. Python provides multiple ways to
format strings, including the older .format() method and the modern
f-strings .
name = "Alice"
age = 30
print("My name is {} and I am {} years old.".format(name, age))
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
Using Expressions in f-Strings
x = 10
y = 5
print(f"The sum of {x} and {y} is {x + y}")
Formatting Numbers
pi = 3.14159265
print(f"Pi rounded to 2 decimal places: {pi:.2f}")
text = "Python"
print(f"{text:>10}") # Right align
print(f"{text:<10}") # Left align
print(f"{text:^10}") # Center align
Important Notes
• Escape Sequences: Use \n , \t , \' , \" , and \\ to handle special
characters in strings.
• Raw Strings: Use r"string" to prevent escape sequence interpretation.
• String Encoding & Decoding: Use .encode() and .decode() to work
with different text encodings.
• String Immutability: Strings in Python are immutable, meaning they
cannot be changed after creation.
• Performance Considerations: Using ''.join(list_of_strings) is more
efficient than concatenation in loops.
Summary
• .format() allows inserting values into placeholders.
• f-strings provide an intuitive and readable way to format strings.
• f-strings support expressions, calculations, and formatting options.