Check out the previous part: Core Python: Part 6
Strings
They are the ordered collection of values of characters. 'hello', and 'he123' are collections of the characters 'h', 'e', 'l', 'l', 'o' and 'h', 'e', '1', '2', '3'. They can be indexed, negative indexed and len() function can be used to find the length of the string. We can use while or for loop to process one character at a time in a string and this pattern is called traversal. Strings are immutable. We can only access individual characters but cannot modify them.
# indexing
my_string = "Hello, World!"
print(my_string[0]) # Output: 'H'
print(my_string[7]) # Output: 'W'
# len()
length = len(my_string)
print(length) # Output: 13
# negative indexing
print(my_string[-1]) # Output: '!'
print(my_string[-3]) # Output: 'l'
my_string = "Hello"
for char in my_string:
print(char)
# Output:
# H
# e
# l
# l
# o
my_string = "Hello, World!"
substring = my_string[7:12] # Extracts characters from index 7 to 11 (inclusive)
print(substring) # Output: 'World'
my_string[3:3] # nothing printed
# immutability
my_string[1] = 'f' # error
String Methods
my_string = "Hello, World!"
upper_case = my_string.upper() # Converts to uppercase
lower_case = my_string.lower() # Converts to lowercase
print(upper_case) # Output: "HELLO, WORLD!"
print(lower_case) # Output: "hello, world!"
# The find() method searches for a substring in a string and returns the index
# of the first occurrence. If not found, it returns -1.
index = my_string.find("World") # Finds the index of "World"
if index != -1:
print(f"Substring found at index {index}")
else:
print("Substring not found")
# The in operator checks if a substring exists within a string and returns
# True or False.
if "World" in my_string:
print("Substring found")
else:
print("Substring not found")
String Comparison
string1 = "apple"
string2 = "apple"
if string1 == string2:
print("Strings are equal")
if string1 != "banana":
print("Strings are not equal")
# The greater than and less than operators compare strings lexicographically
# (based on their Unicode values). It checks if one string comes before or
# after another in dictionary order.
string1 = "apple"
string2 = "banana"
if string1 < string2:
print("string1 comes before string2")
if string2 > "apple":
print("string2 comes after apple")
# You can compare strings based on their Unicode values using the ord() function
char1 = "a"
char2 = "b"
if ord(char1) < ord(char2):
print("char1 comes before char2")
Important
# The syntax is [start:stop:step]
# start is -1, which is the last character.
# stop is 4, which is exclusive, so it stops before index 4.
# step is -1, indicating reverse traversal.
s = "Hello, World!"
result = s[-1:4:-1]
print(result) # Output: "!dlroW"
# This slicing expression starts from the end of the string (-1) and goes
# backward with a step of -1, effectively reversing the string.
result = s[::-1]
print(result) # Output: "!dlroW ,olleH"
String formatting
- The
.format()
method allows you to format strings by replacing placeholders with values.
name = "Alice"
age = 30
height = 5.8
formatted_string = "Name: {}, Age: {}, Height: {:.2f}".format(name, age, height)
print(formatted_string)
# Named arguments
title = "Python"
level = "beginner"
course = "Learn {subject} programming for {audience}.".format(subject=title, audience=level)
print(course) # Output: "Learn Python programming for beginner."
# specify the width and alignment of the placeholder using the colon :
item = "Banana"
price = 0.49
receipt = "{:<10} - ${:.2f}".format(item, price)
print(receipt) # Output: "Banana - $0.49"
- f-strings
name = "Bob"
age = 25
height = 5.5
formatted_string = f"Name: {name}, Age: {age}, Height: {height:.2f}"
print(formatted_string)
- Older C-Style Formatting (%Operator)
name = "Charlie"
age = 22
height = 6.0
formatted_string = "Name: %s, Age: %d, Height: %.2f" % (name, age, height)
print(formatted_string)
# %d: Integer
# %f: Float
# %s: String