Python Strings

What is String?

String is a sequence of characters surrounded by single or double quotations, where character is a letter in alphabet, a digit, a special symbol like punctuation mark, a space, a tab, etc.

String example:

'Hello World!'  or
"Hello World!"

You can simply print a string like :

print('Hello World') 
print("Hello World")

Output:

Hello World
Hello World

Assigning String to a variable:

strg = "This is a string"
print(type(strg))
print(strg)

Output:

<class 'str'>
This is a string

Note: In Python there is no character type like in Java or C#. So, if define

strg = ‘a’

then strg is also a string.

String Operations:

Determining the length of a String: A string’s length is the number of character available in that string. There are many built-in function in Python language, one of them is len(), which is used to determine the length of the String. Ex:

strg = 'Hello World'
print(len(strg))

Output: 11

String in Python is an array of characters. Simply array is a data structure which contains same type of data in the contiguous memory locations. Positions of the characters in the array start from 0. We can use Square brackets [ ] to access the characters/elements of the string. We will see array in detail in the latter chapters.

Let’s see an example :

strg = "This is a string"
print(strg[0]) 
print(strg[0:4])
print(strg[1:4])
length = len(strg)
print(strg[length-1])
print(strg[0:length])

Output:

T
This
his
g
This is a string

In the above example, we saw how we can get part of the string or sub-string.

Different built-in function for string processing in Python:

FunctionDescriptionExample
len()Returns the length of the string.
strg = “This is a String, it lovely!”
length = len(strg)
print(length)

Output: 31
lower()Converts all the characters of the string to lowercase charactersstrg = “This is a String, it is lovely!”
lower_strg = strg.lower()
print(lower_strg)

Output:
this is a string, it is lovely!
upper()Converts all the characters of the string to uppercase charactersstrg = “This is a String, it is lovely!”
upper_strg = strg.upper()
print( upper_strg )

Output:
THIS IS A STRING, IT IS LOVELY!
replace()Can replace whole or part of the string with another stringstrg = “This is a String, it is lovely!”
print(strg.replace(‘lovely’, ‘not lovely’))
print(strg.replace(‘, it is lovely!’, ‘ ‘))

Output:
This is a String, it is not lovely!This is a String
strip()Removes whitespace from the beginning and the end of the string strg = ” This is a String, it is lovely! “
print(strg.strip())

Output:
This is a String, it is lovely!
split()Splits the string to make smaller or substrings according to the separator and returns an array of the substringsstrg = ” This is a String, it is lovely! “
splitted_str_array = strg.split(‘,’)
print(splitted_str_array)
print(splitted_str_array[0])

Output:
[‘ This is a String’, ‘ it is lovely! ‘]
This is a String