Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slicing a string repeatedly

Tags:

python

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
like image 869
navyad Avatar asked Oct 26 '12 08:10

navyad


People also ask

Does slicing a string create a new string?

When you slice strings, they return a new instance of String. Strings are immutable objects.

What is the time complexity of slicing a string?

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.

What is string slicing example?

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.

Is slicing possible in string?

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.


1 Answers

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].

like image 173
Roman Bodnarchuk Avatar answered Sep 19 '22 18:09

Roman Bodnarchuk