Lesson 6: Useful String Methods

  1. Make all the characters in a string upper case
  2. Make all the characters in a string lower case
  3. Make the first letter of a string capital
  4. Make a string title case
  5. Check if a string is a number
  6. Check the length of a string
  7. Pad a string with zeros

Python gives us many useful methods for dealing with Strings.

1) Make all the characters in a string upper case


#Make all letters in a string upper case
mystring = "to be or not to be"
print(mystring.upper())
Notebook Output

2) Make all the characters in a string lower case


#Make all characters in a string lower case
mystring = "THAT IS THE QUESTION"
print(mystring.lower())
code output

3) Make the first letter of a string capital


#Make first character of a string upper case
mystring = "whether 'tis nobler in the mind to suffer"
print(mystring.capitalize())
Notebook Output

4) Make a string title case

Title case means that the first letter of every word is capitalized


#Use Title case. First character of every word capital.
mystring = "to kill a mockingbird"
print(mystring.title())
Notebook Output

5) Check if a string is a number


#Check if a string is a number
mystring = "1212312"
print(mystring.isnumeric())
Notebook Output

6) Check the length of a string


#check the length of a string
mystring = "To be, or not to be, that is the question"
print(len(mystring))
Notebook Output

7) Pad a string with zeros


id_1 = "12121"
id_2 = "434"
#pads the left side of a string to equal the specified length.
print(id_1.zfill(8))
print(id_2.zfill(8))
Notebook Output

Back to Menu