Common String Functions

Below are the common functinos you may need for this class. Want more? Here is every string function available to you!

String Manipulation

Lowercase a String:

text = "Oranges are my favorite"
text = text.lower()  # the text variable contains a lowercased version

Capitalize a name:

text = "tom hanks"
text = text.title()  # the text variable contains 'Tom Hanks'

Remove (or Replace) Characters:

text = "tom hanks is here"
text = text.replace('s','')  # the text variable contains 'tom hank i here'

Remove Extra Whitespace from the ends:

text = " tom hanks is here  "
text = text.strip()  # the text variable contains 'tom hanks is here'

String Splitting

Splitting a string into many smaller strings is a common operation when dealing with text.

Split on spaces:

text = "Oranges are my favorite"
word_list = text.split()  # creates a List of strings: ['Oranges', 'are', 'my', 'favorite']

Split on a specific string, not just the default spaces:

text = "Oranges are my favorite"
word_list = text.split('are')  # creates a List of strings: ['Oranges ', ' my favorite']

String Testing

You'll need some string testing functions that return True or False:

String Contains Test: Use Python's in operator. You ask if a string is in another string, and Python returns True/False:

text = "Oranges are my favorite"
if "oranges" in text:
   print("I love oranges!")

WARNING: the above won't actually print "I love oranges!". Do you see why not? Oranges is capitalized in the sentence, but not in the test. You often need to lowercase your string values first depending on your needs.

String starts with another string: You may want to specifically know if a string starts with another string, not just if it contains it. Use the startswith(str) function:

s = "Hello my friend!"
if s.startswith("Hello"):
	print('It started with Hello!')

String ends with another string: Same as startswith, but on the back side of the string:

s = "Hello my friend!"
if s.endswith("!"):
    print('Ended with an !')

Need more? Here is every string function available to you. You are free to use any of these as you see fit.