# Create a string and name it string string = 'Python'
# How to access characters in a string? # use [index] to access characters in a string # counting starts from 0 in python first_character = string # Print first character print('The first character in python is: ', first_character)
The first character in python is: P
# If counting from behind, start counting from -1 last_character = string[-1] # Print last character print('The last character in python is: ', last_character)
The last character in python is: n
# How to to substring the characters from a string # use : to substring the characters from position 1 to position 5 (not included) # Print first character print('Characters 1 to 4 in python is: ', string[1:5])
Characters 1 to 4 in python is: ytho
# How to find the lenght (number of characters) of a string? # use len() to return the length of a string print('There are', len(string), 'characters in', string)
There are 6 characters in Python
# How to change all characters to lower case? # use .lower() to put all characters in lower case print(string.lower())
# How to change all characters to upper case? # use .upper() to put all characters in upper case print(string.upper())
# How to join strings together? # use + to join (or concatenate) strings together string = string + ' is awesome!' print(string)
Python is awesome!
# How to replace part or the whole string? # use .replace() to replace part a string print(string.replace('awesome', 'amazing'))
Python is amazing!
# How to check if a string starts with some characters # use .startswith() to check if a string starts with some characters print(string.startswith('Py'))