CH - 4 Strings
Introduction to string manipulation and operations
Strings: A “string” is a data type in Python, composed of a collection of characters which can include letters, numbers, and even special characters. For instance, a person’s name, a sentence, can be stored as a string. Working with strings is common in programs that interact with users, like those that display messages or take input.
- Strings have a lot of built-in functions in Python, making it easy to manipulate text. You can change the case of the text, check if it contains certain characters, or combine multiple strings. Some of the inbuilt functions are
- upper(): This function converts all characters in a string to uppercase. It's useful when you need to standardize text for comparisons or formatting.
- lower(): This function converts all characters in a string to lowercase. It's commonly used when you need to ignore case sensitivity in comparisons or store text in a uniform format.
- capitalize(): This function capitalizes the first letter of a string while converting all other characters to lowercase. It's often used for formatting titles or names.
- count(): This function returns the number of occurrences of a substring within a string. It's helpful when you want to know how many times a particular word or character appears in a text.
- find(): This function searches for a substring within a string and returns the index of the first occurrence. If the substring isn't found, it returns -1. It’s useful for locating specific text within larger strings.
- split(): This function splits a string into a list of substrings based on a specified delimiter (such as a space or comma). It's useful for breaking down text into individual components, such as words or data fields
A few examples of these string methods are as follows
# Suppose we have a test string, say "Assosciation for Computing Machinery"
test_string = "Assosciation for computing machinery"
print(test_string.upper()) # Prints "ASSOSCIATION FOR COMPUTING MACHINERY"
print(test_string.lower()) # Prints "assosciation for computing machinery"
print(test_string.capitalize()) # Prints "Assosciation for computing machinery"
print(test_string.count("s")) # Prints the number of times 's' appears in the string, which is 3 in our case
- Understanding these data types is important because different types of data are handled differently in Python, and using the right type makes your program efficient and accurate.