String slices

Slice is a segment of a string. Selecting a slice is similar to selecting a character. So for example:
>>> s = 'I will be back'
>>> print s[0:6]
I will
>>> print s[6:14]
 be back

The operator [n:m] returns the part of the string from the n-th character to the m-th character, including the first but excluding the last.
If you omit the first index, the slice starts at the beginning of the string. If you omit the second index, the slice goes to the end of the string.
>>> s[:6]
'I will'
>>> s[6:]
' be back'
If the first index is greater than or equal to the second index the result is an empty string, represented by two quotation marks:
>>> s[6:6]
''
Empty string contains no characters and has length 0, but other than that it is the same as any other string.
Exercise – Given that the s = ‘I will be back’ what does s[:] mean?
It means that it will print out the whole string form start to an end.
>>> s[:]
'I will be back'

Nema komentara:

Objavi komentar