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.
'Hello World!' or "Hello World!"
You can simply print a string like :
print('Hello World') print("Hello World")
Hello World Hello World
Assigning String to a variable:
strg = "This is a string" print(type(strg)) print(strg)
<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.
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))
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) print(strg[0:4]) print(strg[1:4]) length = len(strg) print(strg[length-1]) print(strg[0:length])
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:
|len()||Returns the length of the string. ||strg = “This is a String, it lovely!”|
length = len(strg)
|lower()||Converts all the characters of the string to lowercase characters||strg = “This is a String, it is lovely!”|
lower_strg = strg.lower()
this is a string, it is lovely!
|upper()||Converts all the characters of the string to uppercase characters||strg = “This is a String, it is lovely!”|
upper_strg = strg.upper()
print( upper_strg )
THIS IS A STRING, IT IS LOVELY!
|replace()||Can replace whole or part of the string with another string||strg = “This is a String, it is lovely!”|
print(strg.replace(‘lovely’, ‘not lovely’))
print(strg.replace(‘, it is lovely!’, ‘ ‘))
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! “|
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 substrings||strg = ” This is a String, it is lovely! “|
splitted_str_array = strg.split(‘,’)
[‘ This is a String’, ‘ it is lovely! ‘]
This is a String