Skip to main content

3.0 Python: Modify Strings

Python has a set of built-in methods that you can use on strings.

3.1 Upper Case

3.1.1 Example

The upper() method returns the string in upper case:

a = 'Hello World!'
print(a.upper())

3.2 Lower Case

3.2.1 Example

The lower() method returns the string in lower case:

a = "Hello, World!"
print(a.lower())

3.3 Remove Withespace

Whitespace is the space before and/or after the actual text, and very often you want to remove this space.

3.3.1 Example

The strip() method removes any whitespace from the beginning or the end:

a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"

3.4 Replace String

3.4.1 Example

The replace() method replaces a string with another string:

a = "Hello, World!"
print(a.replace("H", "J"))

3.5 Split String

The split() method returns a list where the text between the specified separator becomes the list items.

3.5.1 Example

The split() method splits the string into substrings if it finds instances of the separator:

a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']