8.4 - String Manipulation
What strings are and how to create them
Strings are a fundamental data type in programming, consisting of a sequence of characters. Characters can include letters, numbers, spaces, symbols, and punctuation.
Strings must be enclosed in quotation marks to distinguish them from other types of data. Double quotation marks (" ") are commonly used, but single quotation marks (' ') work too.
Examples of creating strings
Joining strings using concatenation
Concatenation is the process of combining two or more strings to create a new one.
In Python, concatenation is typically done using the + operator. You can add spaces or other characters as needed to make the result readable.
Example of concatenation
This method allows programs to generate customised output by merging strings flexibly.
String indexing and manipulation basics
Strings are sequences, so each character has a position, known as an index. Indexing starts at 0 for the first character.
String indexing example
For example, in the string "PYTHON":
- P is at index 0
- Y is at index 1
- T is at index 2
- And so on, up to N at index 5
Programs provide various methods to manipulate strings, such as changing case, finding lengths, or extracting sections. Methods are functions attached to an object (like a string) and are called using a dot (.) notation, e.g., string.method().
Using string methods in algorithms
Algorithms often use string methods to process and generate new strings based on input data. For instance, you might need to create a username by combining parts of different variables, which could involve slicing (extracting substrings), changing case, and concatenation.
Slicing refers to extracting a portion of a string to form a new one, using methods like those in the table above.
Sometimes, non-string data (like numbers) must be converted to strings using casting, such as the str() function, before concatenation.
Example algorithm: Generating a username
Consider an electricity company that creates a 7-character username from customer data stored in variables: town (a string), age (an integer), and surname (a string). The username combines:
- The first 3 letters of the town in uppercase.
- The customer's age as 2 digits.
- The first and last letters of the surname in lowercase.
Here is a Python algorithm to achieve this:
This approach demonstrates how methods can be chained (e.g., slicing then upper()) and adapted for different inputs, showing there are multiple ways to solve the same problem.