String Manipulations

In [87]:
# Create a string and name it string
string = 'Python'
In [88]:
# How to access characters in a string?
#  use [index] to access characters in a string
#  counting starts from 0 in python
first_character = string[0]
# Print first character
print('The first character in python is: ', first_character)
The first character in python is:  P
In [89]:
# 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
In [90]:
# 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
In [91]:
# 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
In [92]:
# How to change all characters to lower case?
#  use .lower() to put all characters in lower case 
print(string.lower())
python
In [93]:
# How to change all characters to upper case?
#  use .upper() to put all characters in upper case 
print(string.upper())
PYTHON
In [94]:
# How to join strings together?
#  use + to join (or concatenate) strings together
string = string + ' is awesome!'
print(string)
Python is awesome!
In [96]:
# How to replace part or the whole string?
#  use .replace() to replace part a string
print(string.replace('awesome', 'amazing'))
Python is amazing!
In [99]:
# 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'))
True