Handling Strings datatype in Python

Ruma Sinha
4 min readJul 21, 2020

Strings are the scalar datatype in Python. Strings are sequence of characters.

Strings are either in single quotes or double quotes like ‘school’ or “school”.

print(‘school’)
print(“school”)

Let us define a variable say name and assign the value Mary to this variable:
name = ‘Mary’
print(name)

Strings are arrays with each character at a particular position starting with position 0.

a = “Paris is beautiful city!”
print(a[0])
print(a[1])

print(a[-1]) will print the first character from the end.

print(len(a)) will give the number of characters in the whole string

a[2:5] gives the characters from 2nd position to 5th. 2nd position is inclusive. 5th position is exclusive.

lower() converts a string to lower case. upper() converts a string to upper case.

replace(‘x’,’y’) will replace the occurrence of the character “x” with the character “y”.

“in” is used to check whether a particular string/character exists in a string variable.

“not in” is used to check whether a particular string/character does not exist in a string variable.

“+” is used to concatenate various strings. In order to provide space between various strings, we can concatenate ” ” with other strings.

If we have single quote in a string then we can have double quotes around the whole string as shown below:

If we have double quotes in a string then we can have single quote around the whole string as shown below:

a = “Good Morning”
print(a.split())

split will be splitting the whole sentence into words based on the spaces between each word.

a = ” Good Morning “
print(a.strip())
print(a.lstrip())
print(a.rstrip())

strip function will remove all the spaces on either side of a string variable. rstrip will remove all the spaces on the right side of the variable. lstrip will remove all the spaces on the left side of the variable.

len() function gives the number of characters of a string variable.

We see below that the number of characters in the variable a is 14. When we remove the spaces on either side of a then the number of characters in a equals 12. When we remove either right or left space of the variable then the number of characters equals 13.

find() function returns the index of the character if it is present in the string. For example, a.find(‘Good’) returns 0 index which is the position of the first character “G”. a.find(‘Mor’) returns index 5 , the position of the character “M”.

Let us understand the code:

a=5…we are assigning an integer to variable a. We can see the variable type with the function type(). Hence, type(a) shows the class of a as “int”(integer)

We can convert integer a to string a using the str function. hence we assign str(a) to the variable b. When we check the variable type of b we can see it is of string type.

--

--