Repeated slicing works on tuples and lists just fine:
>>> tuple = ("nav", "yad")
>>> tuple[0]
'nav'
>>> tuple[0][0]
'n'
But with strings:
>>> name="university"
>>> name[0]
'u'
The weird thing here is, when I try repeated slicing over string name variable,
there is nothing at name[0][0]
or name[0][-1]
, so why does it show "u"
?
>>> name[0][0]
'u'
>>> name[0][-1]
'u'
And if something is at name[0][0]
then why not on other indexes?
>>> name[0][1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
When you slice strings, they return a new instance of String. Strings are immutable objects.
Short answer: str slices, in general, copy. That means that your function that does a slice for each of your string's n suffixes is doing O(n2) work. That said, you can avoid copies if you can work with bytes -like objects using memoryview s to get zero-copy views of the original bytes data.
It's known as string slicing. The syntax that you use looks really similar to indexing. Instead of just one value being put in the square brackets, you put two with a colon ( : ) in between the two. So in this example, s is the string and m and n are the two values.
Slicing StringsYou can return a range of characters by using the slice syntax. Specify the start index and the end index, separated by a colon, to return a part of the string.
String is a sequence. String of one character is still a sequence with one element. So with a string you can do name[0][0][0][0]...
and it will work fine. Same with index -1
, that returns last element of a sequence:
>>> name[0][0]
'u'
>>> name[0][0][-1]
'u'
>>> name[0][0][-1][-1]
'u'
name[0][1]
obviously fails because there is only one element in the string name[0]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With