Python Modify Strings
Modify Strings in Python
Python has several built-in methods for modifying strings:
- Uppercase: Convert the string to uppercase:
python
1a = "Hello, World!"
2print(a.upper()) # Output: 'HELLO, WORLD!'
- Lowercase: Convert the string to lowercase:
python
1print(a.lower()) # Output: 'hello, world!'
- Remove Whitespace: Use
strip()
to remove spaces from the beginning and end:
python
1a = " Hello, World! "
2print(a.strip()) # Output: 'Hello, World!'
- Replace String: Replace characters or substrings using
replace()
:
python
1print(a.replace("H", "J")) # Output: 'Jello, World!'
- Split String: Use
split()
to split a string into a list based on a separator:
python
1print(a.split(",")) # Output: ['Hello', ' World!']