Skip to content

String & Slicing of Collection

surendrabisht edited this page Jul 13, 2020 · 3 revisions

String refers to text. Internally it is a collection of characters. just like list of characters or array of characters (just like other languages).

Strings are ordered sequences of character data. Indexing allows you to access individual characters in a string directly by using a numeric value. String indexing is zero-based: the first character in the string has index 0, the next is 1, and so on.

String in python is stored internally as below and characters can be accessed using the indexes.

String indexing


Slicing

Below, we can see the slicing can be done using syntax [:] ,[::]

String Slicing

Just like String, other collections can be sliced the same way. Here we have discussed all the ways we could slice a collection. Try using the slicing with string and list on your own as well.


Strings are Immutable
Strings are immutable in Python just like in c# or Java programming language.
text="tutorial"
text[0]="T"   # this will give error as we cannot change strings. Rather we can assign a new string to this variable text
text ="Tutorial"    # this is possible
text= text.replace("t","T")    # replace function which used old string and produces new string and returns it. this is possible

Clone this wiki locally