String Functions In Python

  • more functions you can do on strings
tiger_fact = "the stripes on a Tiger are unique, similar to the human fingerprint"


#make everything lowercase or uppercase, use .lower() or .upper()
print(tiger_fact.lower())
print(tiger_fact.upper())
the stripes on a tiger are unique, similar to the human fingerprint
THE STRIPES ON A TIGER ARE UNIQUE, SIMILAR TO THE HUMAN FINGERPRINT
#count how many times an argument appears
#don't forget quotes
print(tiger_fact.count("the"))
2
#find a specific index
#index is the number of a character in a string
print(tiger_fact.find("unique"))
#27 means the letter "u" is the 27th character
27
#replace something in a string, there are 2 parts

#format: variable.replace('thing you want replaced', 'replacement')
tiger_fact.replace('Tiger', 'zebra')
#this will not work on it's own. To make it work, there are 2 options:

#option1: make new var 
new_tiger_fact = tiger_fact.replace('Tiger', 'zebra')
print(new_tiger_fact)

#option2: replace old var with new var
tiger_fact = tiger_fact.replace('Tiger', 'zebra')
print(tiger_fact)
the stripes on a zebra are unique, similar to the human fingerprint
the stripes on a zebra are unique, similar to the human fingerprint

Concat

  • stands for concatinate
  • join multiple variables together
fish = "fish"
fish1 = "angel"
fish2 = "cat"
fish3 = "puffer"


bad_format_species = fish1 + fish + fish2 + fish + fish3 + fish
print(bad_format_species)
#you can also do this directly under print instead of making a new var

#to better format these fishes, add commas and spaces as separate strings in variable
good_format_species = fish1 + fish + ', ' + fish2 + fish + ', ' + fish3 + fish
print(good_format_species)
angelfishcatfishpufferfish
angelfish, catfish, pufferfish
Formatted string basics
  • when you are concating a lot of variables, using plus signs and individual strings for spaces gets messy
  • formatted strings make it easier to read and keep track of everything
  • use placeholders {} then replace them later on with .format()
better_format_species = '{}{}, {}{}, and {}{} are my favorite fish!' .format(fish1,fish,fish2,fish,fish3,fish)
print(better_format_species)
angelfish, catfish, and pufferfish, are my favorite fish!