This article is an Easy Guide on Creation, Indexing and Slicing of python String. Python String stored text information in single or double quotation mark. Python understands the string to be a sequence of letters in a specific order. This means we will be able to use indexing to get any particular letters (like the second letter, or the last letter).
1. Creating Strings
In Python, you can create strings using single (‘ ‘), double (” “) or triple (”’ ”’ or “”” “””) quotes .Triple-quoted strings are useful for multiline text . Let’s create a String!
myString=” Nullification “
Let’s create a multiline String using triple (”’ ”’ or “”” “””) quotes
StrMultiline= ”’ This is Kumar.
I am student.
I learn 8 hr each day. ”’
Escape characters allow you to include special characters within strings. Below are Escape characters which you should know off hand.
2. String Indexing
Strings are sequences of characters . The moment we create a String python assign an index to each characters as shown in below image. As the created sting starts with a space so index 0 stores a space .
You can access individual characters or slices using indexing and slicing. We can use indexing to access any character of String. Indexing starts at 0 so, ‘N’ is at 1st , ‘U’ at 2nd, ‘l’ at 3rd position and so on . Negative index count from the end of the string. Below code will get character at index 2.
myString [ 2 ]
3. String Slicing
For Slicing, we can pass start , end and steps index separated by : to grabs a slice of string . It uses the syntax [start : end : step] to grab letters starting at index start till index end -1 using a step. Below codes start at index 1 and pull till 3rd index . As there is nothing mentioned in step so by default it’s 1 .
myString [ 1 : 4 ]
Start pulling all letters starts from index 1 till 9th and don’t skip any letters.
myString [ 1 : 10 : 1 ]
Start pulling all letters starts from index 1 till 9th and skip a letter each time.
myString [ 1 : 10 : 2 ]
If we keep any of start , end , step as blank that means start =0 , end = last index of string and step=1 . So below code will start pulling all letters starts from index 0 till end and don’t skip any letter.
myString [ : : ]
As we discussed , Negative index counts from the end of the string .When we use step =-1 that means we have to start from the last index of the string . Life Python List , below code is the good way to reverse the string too without using any function .
myString [ : : -1 ]
4. String Modification
Strings in Python are immutable, meaning you cannot change their contents once they’re created. If you try to modify a string you get error as shown below :