Python built-in String Functions

Python contains many useful built-in functions and methods to accomplish common tasks.

The join() function

join() – joins a list of strings with another string as a separator.

Example:

print(["Honda", "Yamaha", "Suzuki"])
print(", ".join(["Honda", "Yamaha", "Suzuki"]))

The terminal output will be:

ddn_ro@linux:~/Desktop$ python file.py
['Honda', 'Yamaha', 'Suzuki']
Honda, Yamaha, Suzuki
ddn_ro@linux:~/Desktop$

The replace() function

replace() – replaces one substring in a string with another.

Example:

print("Yamaha is the best")
print("Yamaha is the best".replace("Yamaha", "Honda"))

The terminal output will be:

ddn_ro@linux:~/Desktop$ python file.py
Yamaha is the best
Honda is the best
ddn_ro@linux:~/Desktop$

The startswith() and endswith() function

startswith() and endswith() – determine if there is a substring at the start and end of a string, respectively.

Example:

print("Honda is the best.".startswith("Honda"))
print("Honda is the best.".startswith("Yamaha"))
print("Honda is the best.".endswith("best."))
print("Honda is the best.".endswith("worst."))

The terminal output will be:

ddn_ro@linux:~/Desktop$ python file.py
True
False
True
False
ddn_ro@linux:~/Desktop$

The lower() and upper() function

lower() and upper() – are used to change the case of a string.

Example:

print(“Honda is the best.”.upper()) print(“HONDA IS THE BEST”.lower())

The terminal output will be:

ddn_ro@linux:~/Desktop$ python file.py
HONDA IS THE BEST.
honda is the best
ddn_ro@linux:~/Desktop$

The split() function

split() – is the opposite of join, turning a string with a certain separator into a list.

Example:

print("Honda, Yamaha, Suzuki".split(", "))

The terminal output will be:

ddn_ro@linux:~/Desktop$ python file.py
['Honda', 'Yamaha', 'Suzuki']
ddn_ro@linux:~/Desktop$

Leave a Reply