Manipulating Mixed Strings in Python
Now that we can identify the digits and letters within a mixed string, let's explore the various ways to manipulate and process these components in Python.
Extracting Digits and Letters
Using the techniques discussed in the previous section, you can extract the digits and letters from a mixed string separately.
import re
mixed_string = "LabEx123"
## Extract digits
digits = re.findall(r'\d', mixed_string)
print(f"Digits: {', '.join(digits)}")
## Extract letters
letters = re.findall(r'[a-zA-Z]', mixed_string)
print(f"Letters: {', '.join(letters)}")
This will output:
Digits: 1, 2, 3
Letters: L, a, b, E, x
Removing Digits or Letters
If you need to remove either the digits or the letters from a mixed string, you can use the re.sub()
function from the re
module.
import re
mixed_string = "LabEx123"
## Remove digits
string_without_digits = re.sub(r'\d', '', mixed_string)
print(f"String without digits: {string_without_digits}")
## Remove letters
string_without_letters = re.sub(r'[a-zA-Z]', '', mixed_string)
print(f"String without letters: {string_without_letters}")
This will output:
String without digits: LabEx
String without letters: 123
Separating Digits and Letters
In some cases, you may want to separate the digits and letters into two distinct strings. You can achieve this by using a combination of the techniques we've discussed.
import re
mixed_string = "LabEx123"
## Separate digits and letters
digits = re.findall(r'\d', mixed_string)
letters = re.findall(r'[a-zA-Z]', mixed_string)
digit_string = ''.join(digits)
letter_string = ''.join(letters)
print(f"Digit string: {digit_string}")
print(f"Letter string: {letter_string}")
This will output:
Digit string: 123
Letter string: LabEx
By mastering these manipulation techniques, you can effectively work with mixed strings, extracting, modifying, and processing the individual components as per your programming requirements.