It is helpful to think of a string as an ordered sequence. Each element in the sequence can be accessed using an index represented by the array of numbers:
The first index can be accessed as follows:
[Tip]: Because indexing starts at 0, it means the first index is on the index
We can access index 6:
# Print the element on index 6 in the stringprint(Name[6])
Moreover, we can access the 13th index:
# Print the element on the 13th index in the stringprint(Name[13])
We can also use negative indexing with strings:
Negative index can help us to count the element from the end of the string.
The last element is given by the index -1:
# Print the last element in the stringprint(Name[-1])
# Print the first element in the string
print(Name[-15])
We can find the number of characters in a string by using len
, short for length:
# Find the length of string
len("Michael Jackson")
We can obtain multiple characters from a string using slicing, we can obtain the 0 to 4th and 8th to the 12th element:
[Tip]: When taking the slice, the first number means the index (start at 0), and the second number means the length from the index to the last element you want (start at 1)
We can also input a stride value as follows, with the '2' indicating that we are selecting every second variable:
# Get every second element. The elments on index 1, 3, 5 ...
Name[::2]
We can also incorporate slicing with the stride. In this case, we select the first five elements and then use the stride:
# Get every second element in the range from index 0 to index 4
Name[0:5:2]
We can concatenate or combine strings by using the addition symbols, and the result is a new string that is a combination of both:
# Concatenate two stringsStatement = Name + "is the best"Statement
[
To replicate values of a string we simply multiply the string by the number of times we would like to replicate it. In this case, the number is three. The result is a new string, and this new string consists of three copies of the original string:
No comments:
Post a Comment