Strings

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.

8.1 Introduction

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.

8.2 Strings

8.2.1 Accessing Characters in a String

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 '!'
    • Accessing out-of-bound indices (e.g., 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.

8.2.2 String is Immutable

Strings are immutable; their content cannot be altered post-creation. For instance, trying to assign str1[1] = 'a' raises a TypeError.

8.3 String Operations

Python allows various operations on strings:

8.3.1 Concatenation

The + operator joins two strings. For example, ordinating:

str1 = 'Hello'
str2 = 'World!'
str1 + str2  # Output: 'HelloWorld!'

8.3.2 Repetition

The  operator repeats strings. Example:

str1 * 2  # Output: 'HelloHello'

8.3.3 Membership

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

8.3.4 Slicing

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].

8.4 Traversing a String

Strings can be traversed using loops:

Using a for loop:

for ch in str1:
    print(ch, end='')

Using a while loop:

index = 0
while index < len(str1):
    print(str1[index], end='')
    index += 1

8.5 String Methods and Built-in Functions

Python provides many built-in functions to manipulate strings effectively. Below are some common methods:

  • len(): Returns the string's length.
  • title(): Converts to title case.
  • lower(): Converts to lowercase.
  • upper(): Converts to uppercase.
  • count(sub): Counts occurrences of a substring.
  • find(sub): Finds the first occurrence of a substring.
  • replace(old, new): Replaces substring.

8.6 Handling Strings

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.

Example Program - Count Character Occurrences

# Function to count character occurrences

def charCount(ch, st):
    count = 0
    for character in st:
        if character == ch:
            count += 1
    return count

Example Program - Vowel Replacement

# Function to replace vowels

def replaceVowel(st):
    newstr = ''
    for character in st:
        if character in 'aeiouAEIOU':
            newstr += '*'
        else:
            newstr += character
    return newstr

Conclusion

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.

Key terms/Concepts

  1. A string is a sequence of UNICODE characters enclosed in quotes.
  2. Strings are indexed, starting from 0 to n-1; negative indices count from the end.
  3. Strings in Python are immutable and cannot be altered after creation.
  4. String operations include concatenation, repetition, membership, and slicing.
  5. Slicing syntax: str[n:m] to retrieve a substring.
  6. Strings can be traversed using for and while loops.
  7. Python provides many built-in string methods for manipulation (e.g., len(), upper(), lower()).
  8. Programs can be defined to manipulate strings beyond built-in capabilities.

Other Recommended Chapters