Categories

Dec 12, 2019 in Python

Q: Python string

1 Answer

Dec 12, 2019
In python, strings can be created by enclosing the character or the sequence of characters in the quotes. Python allows us to use single quotes, double quotes, or triple quotes to create the string.

Consider the following example in python to create a string.

str = "Hi Python !"  

Here, if we check the type of the variable str using a python script

print(type(str)), then it will print string (str).  

In python, strings are treated as the sequence of strings which means that python doesn't support the character data type instead a single character written as 'p' is treated as the string of length 1.

Strings indexing and splitting

Like other languages, the indexing of the python strings starts from 0. For example, The string "HELLO" is indexed as given in the below figure.

Python String

As shown in python, the slice operator [] is used to access the individual characters of the string. However, we can use the : (colon) operator in python to access the substring. Consider the following example.

Python String

Here, we must notice that the upper range given in the slice operator is always exclusive i.e., if str = 'python' is given, then str[1:3] will always include str[1] = 'p', str[2] = 'y', str[3] = 't' and nothing else.

Reassigning strings

Updating the content of the strings is as easy as assigning it to a new string. The string object doesn't support item assignment i.e., A string can only be replaced with a new string since its content can not be partially replaced. Strings are immutable in python.

Consider the following example.

Example 1

str = "HELLO"  

str[0] = "h"  

print(str)
Click here to read more about Python
Click here to read more about Insurance

Related questions

Madanswer
Jun 28 in Python
Dec 22, 2019 in Python
May 17 in Python
...