- Get link
- X
- Other Apps
Python - Modify Strings
Python comes with some ready-to-use tools that make working with text easier.
Upper Case
Example
If you apply the upper() method to a string in Python, it will convert all the letters in the string to uppercase and return the modified string:
x = "Hello, World!"
print(x.upper())
Lower Case
Example
If you apply the lower() method to a string in Python, it will convert all the letters in the string to uppercase and return the modified string:
x = "Hello, World!"
print(x.lower())
Remove Whitespace
The term "whitespace" refers to the space that appears before and/or after the text itself, and it is often desirable to eliminate this space.
Example
Using the `strip()` method, you can eliminate any whitespace located at the start or end of a string:
x = " Hello, World! "
print(x.strip()) # returns "Hello, World!"
Replace String
Example
With the `replace()` method, you can substitute one string with another string:
x = "Hello, World!"
print(x.replace("e", "o"))
Split String
By making use of the `split()` method, you can obtain a list where the elements are formed by dividing the original text at the specified separator.
Example
The `split()` method breaks down a string into smaller parts based on a specified separator:
x = "Hello, World!"
print(x.split(",")) # returns ['Hello', ' World!']
Comments
Post a Comment