Translate

Monday, October 13, 2025

PP_String Manipulation


Contents

1. Introduction to String Manipulation

A string is a sequence of characters arranged in a specific order, utilized for text storage. In many programming languages, strings are unchangeable (altered or sliced), indicating that once a string is formed, its content remains fixed. Altering case or slicing leads to the creation of a different string.

Properties of Strings

Immutability: A string is said to be immutable if once a string object is created, you cannot change individual characters within it. 

Example: If you try to change the first letter of the string "Class" to "G", the language creates a new string "Glass" instead of modifying the original memory space.

Indexing: Strings is an ordered collection of characters, and each character corresponds to an index or position number. Forward Indexing starts at 0 for the first character, while backward Indexing starts at -1 for the last character.

Examples

String         C l a s s

Forward Indexing  0 1 2 3 4

Backward Indexing -5 -4 -3 -2 -1

Length of a String

Length of a string is the number of characters in that string. It is also known as its length, and can be found using a built-in function len(s) in Python or s.length in JavaScript/Java.

String manipulation is the programmatic alteration, processing, or examination of text strings. This encompasses a variety of operations aimed at modifying, extracting, or combining textual information. And strings come with a rich set of built-in methods (functions attached to the string object) for common tasks. Examples include:

2. Case Conversion

Case Conversion

    a) .lower(): Converts all characters in the string to lowercase.

       Example:

       name = "UGANDA"; 

       name.lower()

       "uganda"

    b) .upper(): Converts all characters in the string to uppercase.

       Example:

       word = "Uganda"; word.upper()

       "UGANDA"

    c) .capitalize(): Converts the first character of the string to uppercase and the rest to lowercase.

       Example:

       s = "my name"; s.capitalize()

       "My name"

    d) .title(): Converts the first character of every word to uppercase.

       s = "my name"; s.title()

       "My Name"

3. Searching and Testing

Searching refers to the process of determining the existence, position, or frequency of a substring within a larger string. Important techniques for searching consist of functions that aid in this are as follows:

Testing involves confirming that string operations and functions work as intended. This utilizes different techniques to validate the output and functionality of string manipulations, ensuring they yield the correct results and manage various scenarios correctly.

    a) .find(sub): This returns the lowest index of the substring, and returns -1 if not found.

       Example:

       "uganda".find("g")

       1

    b) .isalpha(): This returns True if all characters are alphabetic (a-z, A-Z) and non-empty.

       Example:

       "primary7".isalpha()

       False

       

    c) .startswith(prefix): Returns True if the string begins with the specified prefix.

       Example:

       "Class.csv".startswith("Class")

       True

       

    d) .endswith(suffix)

       Returns True if the string ends with the specified suffix.

       "class.png".endswith(".txt")

       False


3. Modification and Cleaning

Modifying or manipulating strings in Python allows one to handle textual data efficiently. It enables creation, altering, and controls strings seamlessly. This is especially when one needs to save time and enhance coding quality. Examples include:

    a) .replace(old, new): Replaces all occurrences of old substring with new substring.

       "Class".replace("C", "G")

       "Glass"

    b) .strip(): Returns a copy of the string with leading and trailing whitespace removed.

       Example:

       " \n hello \t ".strip()

       "hello"

    c)  .split(sep): Splits the string into a list of substrings based on a delimiter (sep).

       Example:

       "B,I,T".split(",")

       ['B', 'I', 'T']

    d) .join(iterable): Concatenates or joins elements of an iterable like a list. 

       Example:

       "*".join(["1", "2", "3", "4"])

       "1*2*3*4"


3. String Formatting

String formatting in Python, often referred to as string interpolation, involves generating dynamic strings by inserting values such as variables, expressions, or function calls) into a predetermined text template. Examples of string formatting includes:

.format() Method (Standard Style): The values are passed as arguments to the .format() method and uses curly braces {} as placeholders. 

Example:

fruit = "apple"

price = 1000.00

output = "The {} costs Ugx{:.2f}.".format(fruit, price)

Output is: "The apple costs Ugx 1000.00" 

Where, :.2f defines the decimal places

Positional Formatting (Old Style / C-Style): This uses placeholders like %s (string), %d (integer), %f (float), and uses values are passed in a tuple after the string.

Example:

# Example

mass = 50

name = "John"

output = "My name is %s and I weigh %d Kg." % (name, mass)

# Result: "My name is John and I weigh 50kg."


F-Strings (Formatted String Literals): Precede the string with an f (or F). Variables and expressions are placed directly inside the curly braces {}. This is the cleanest and most readable method.

Example

temp = 22.5

city = "Kampala"

output = f"The temperature in {city} is {temp:.1f}°C."

The output is: "The temperature in Kampala is 22.5°C."

Slicing

Slicing extracts a portion (substring) of a string. It always returns a new string.

The syntax is string[start:stop:step].

Where:

start: The index where the slice begins (inclusive).

Stop: The index where the slice ends (exclusive—the character at this index is NOT included).

Step: The increment between indices (defaults to 1).

Example:

For the string DECEMBER

s[0:3] Starts at index 0, stop before index 3. "DEC"

s[5:] Start at index 5, go until the end. "BER"

s[:4] Start from the beginning, stop before index 4. "DECE"

s[1:-2] Start at index 1, stop before the second-to-last character. "ECEMBE"


No comments:

Post a Comment