Let us setup the variable MyString
MyString = "abcdef"
Exercise 1: Setup variable and print it out.
MyString = "abcdef"
Exercise 1: Setup variable and print it out.
String content | a | b | c | d | e | f |
String index from left | 0 | 1 | 2 | 3 | 4 | 5 |
String index from right | -6 | -5 | -4 | -3 | -2 | -1 |
Above is a table showing how we will reference this string variable.
print(MyString)
The most basic print is to print a whole string.
Output: abcdef
print(MyString[0:3])
Prints characters 0 to 3.
Output: abc
print(MyString[3::])
Prints from character 3 to the end. Advantage of this is that you don't need to know the length of the string. Notice the ::
Output: def
print(MyString[0:6:2])
The third part of the command is the step. This example prints every alternate character. It's ace isn't it?
Output: ace
print(MyString[-1:-7:-1]) #prints every character backwards
We can start at the right side of the string and work backwards. -1 is the last character of the string.
Output: fedcba
print(MyString[0:-2])
We can also print until -2 from the end.
Output: abcd
Exercise 2: Come up with your own variable and slice it forwards, backwards and skip a letter or two.
print(MyString)
The most basic print is to print a whole string.
Output: abcdef
print(MyString[0:3])
Prints characters 0 to 3.
Output: abc
print(MyString[3::])
Prints from character 3 to the end. Advantage of this is that you don't need to know the length of the string. Notice the ::
Output: def
print(MyString[0:6:2])
The third part of the command is the step. This example prints every alternate character. It's ace isn't it?
Output: ace
print(MyString[-1:-7:-1]) #prints every character backwards
We can start at the right side of the string and work backwards. -1 is the last character of the string.
Output: fedcba
print(MyString[0:-2])
We can also print until -2 from the end.
Output: abcd
Exercise 2: Come up with your own variable and slice it forwards, backwards and skip a letter or two.