This chapter explores strings in Python, covering their creation, properties, operations, and built-in methods. It emphasizes strings as immutable sequences of Unicode characters and illustrates various string manipulations and traversals.
In this chapter, we delve into strings, a vital data type in Python. Strings are sequences of one or more UNICODE characters, encapsulated within either single, double, or triple quotes.
Strings are indexed collections of characters, where the first character is indexed at 0. For example:
str1 = 'Hello World!'
str1[0] yields 'H'str1[6] yields 'W'str1[11] gives the last character '!'str1[15]) raises an IndexError.Negative indexing allows access from the end of the string, where the last character is -1. It is worth noting that string lengths can be obtained using the len() function.
Strings are immutable; their content cannot be altered post-creation. For instance, trying to assign str1[1] = 'a' raises a TypeError.
Python allows various operations on strings:
The + operator joins two strings. For example, ordinating:
str1 = 'Hello'
str2 = 'World!'
str1 + str2 # Output: 'HelloWorld!'
The operator repeats strings. Example:
str1 * 2 # Output: 'HelloHello'
Two membership operators in and not in check if one string exists within another. For instance:
'W' in str1 # Output: True
'X' not in str1 # Output: True
Slicing extracts a part of the string by defining start and end indices. For instance:
str1[1:5] # Output: 'ello'
This can also utilize a step size to increase the slicing interval: str1[n:m:k].
Strings can be traversed using loops:
for loop:for ch in str1:
print(ch, end='')
while loop:index = 0
while index < len(str1):
print(str1[index], end='')
index += 1
Python provides many built-in functions to manipulate strings effectively. Below are some common methods:
Users can define functions to perform specialized operations. Example programs include counting character occurrences, vowel replacement, reversing strings, and palindrome checks. These exercises enhance understanding and practical usage of string manipulation in Python.
# Function to count character occurrences
def charCount(ch, st):
count = 0
for character in st:
if character == ch:
count += 1
return count
# Function to replace vowels
def replaceVowel(st):
newstr = ''
for character in st:
if character in 'aeiouAEIOU':
newstr += '*'
else:
newstr += character
return newstr
The chapter provides a comprehensive understanding of strings in Python, focusing on their properties, operations, and built-in functionalities, which cater to diverse manipulation needs.
str[n:m] to retrieve a substring.