Python Key Skills - 3

Table of Contents

1 Python Key Skills 3

Learn It - Change a string to all upper case or lower case

change a string to all upper case

  • Python has a built-in function for this.
myString = "Hello world!"
print(myString.upper())
  • the above code will print out "HELLO WORLD!".BUT
  • the variable myString is not changed. To change variable myString you need to re-assign the value to it.
myString = "Hello world!"
myString = myString.upper()

change a string to all lower case

  • Python has a built-in function for this.
myString = "Hello world!"
print(myString.lower())
  • the above code will print out "hello world!".BUT
  • the variable myString is not changed. To change variable myString you need to re-assign the value to it.
myString = "Hello world!"
myString = myString.lower()

To extract any part of a string

  • Python treats string as a list of characters with index.
  • in the string "I love cheese", the character "I" will have an index 0, followed by a space with an index 2, and so on.
myString = "I love cheese"
# To get the first letter/character
firstChar = myString[0]

# To get the last letter/character
lastChar = myString[-1]

# To get the last 4 letters/characters
last4Chars = myString[-4:0]


# To get the first 4 letters/characters
first4Chars = myString[0:4]

# To get the letters/characters between index 3 and 5
last4Chars = myString[3:6]

# To get the letters/characters starting from 3 but skipping one between until index 8
last4Chars = myString[3:8:2]