A sequence of characters enclosed with single quotes(‘ and ‘) or double quotes(” and “) are called strings. In order to create a string variable just declare a name and assign a string value to it as given ahead.

name = ‘learner’ 
website = “codippa.com”

Checking type of string variable
Just to verify that a variable holds a string and is of string type, use type function with the name of the variable as argument as below.

name = "codippa"
type(name)        # prints <class 'str'>
type("python")    # prints <class 'str'>

Accessing characters of string
Individual characters of a python string can be accessed using their index within square brackets([ and ]) with the index of first character as 0. Example,

print(name[0])       # will return n

Character indexing starts from left to right with 0 as the index of left most character, 1 as index of second character from left and so on. In order to access rightmost(or last) character, you can use an index of length of the (string – 1) or simply -1. Example,

name = "codippa"     # length of string is 7
print(name[6])       # access last character as (7 - 1)
print(name[-1])      # access last character using -1

Thus, characters of strings in python can also be accessed from right to left using index starting from -1 with index of rightmost character as -1, index of second character from right as -2 and so on.

Python does not contain a character data type unlike most programming languages.

Accessing string characters within range
It is possible to access multiple characters of a string by their indexes. This is done by taking the indexes of the range of characters that need to be accessed and separating them by  a colon(:) as shown below. Characters between start index and (end index -1) are included. In order to access all characters after a certain index just use that index followed by a colon(:), that is leave the end index.

name = "codippa"
print(name[2:5])   # prints characters from index 2 to 4, that is, dip
print(name[2:])    # prints all characters after character at second index, that is, dippa

It is also possible to use negative indexes while accessing characters with -1 as the index of rightmost character, -2 as second last character and so on. Note that indexes should be in order from left to right always.

name = "codippa"
print(name[-3:-1])     # prints pp
print(name[-3:])       # prints ppa


Liked the article ? Spread the word...

Leave a Reply