String manipulation in python

There are many functions to manipulate strings (characters surrounded by quotes "hello") to get a desired result.

Python has so many built-in functions to manipulate strings.
Let's get straight to business of the most commonly used functions.

capitalize()

Returns a copy of the string with its first letter capitalized.

name = "john"
print(name.capitalize())
>>> John

lower()

Returns a copy of the string with all the characters converted to lowercase.

name = "Jack Ma"
print(name.lower())
>>> jack ma

use upper() for uppercase conversion

count(sub[, start[, end]])

count() takes 1 required argument and two optional arguments

counts the number of times "sub" appeared in the string, the "start" and "end" options determines where to start counting and where to end the count.

name = "johndoe"
print(name.count("o"))  # 'o' appeared 2 times
>>> 2

isalpha()

Returns True if all characters in the string are alphabetic and there is at least one character, otherwise returns False.

name = "johndoe"
print(name.isalpha())
>>> True

name = ""
print(name.isalpha())
>>> False  # name is an empty string

name = "num34"
print(name.isalpha())
>>> False

You can also use isdigit(), isdecimal(), isnumeric(), etc...

islower()

Returns True if all characters in the string are lowercase.

name = "johndoe"
print(name.islower())
>>> True

You can also use isupper(), to check for uppercase (Capital letters)

replace(old, new[, count])

replace() takes 2 required arguments and 1 optional argument

Returns a copy of the string with all "old" values replaced by "new". "count" determines how many times it should be replace (it is optional)

name = "johndoe was good"
print(name.replace("o", "z"))
>>> jzhndze was gzzd

quote = "music is life"
print(quote.replace("i", "non", 2))
>>> musnonc nons life

endswith(suffix[, start[, end]])

endswith() takes 1 required argument and two optional arguments

Returns True if the string ends with the specified suffix, otherwise returns False. The "start" and "end" options determines where to start checking for the suffix and where to end the search.

name = "johndoe"
print(name.endswith("o"))
>>> False

language = "French"
print(language.endswith("ch"))
>>> True

split(sep=None, maxsplit=- 1)

split() takes 1 required argument and 1 optional argument

Returns a list of the words in the string, using "sep" as the delimiter(splitting) symbol.

name = "life is good"
print(name.split(" "))  # splits the string by space
>>> ["life", "is", "good"]

Conclusion

There are a lot of in-built functions you can use. Too many to list them all here.
You can do a lot of cool things with all these functions. I will leave resources to read more on them below.

Thanks for reading, let me know if I should add more. Hope to hear your feedback.

Bonus Resources

17