Strings in Python
Strings in Python
● Text Type
● Numeric Type
● Sequence Type
● Mapping Type
● Set Types
● Boolean Type
● Binary Type
Here, string belongs to the category text type.Now let’s discuss the string data type further in
detail.
Strings:
A string represents a group of characters. Strings are important because most of the data that
we use in daily life will be in the form of strings. For example, the names of persons, their
addresses, vehicle numbers, their credit card numbers, etc. are all strings. In Python, the str
data type represents a string.
Creating strings:
We can create a string in Python by assigning a group of characters to a variable. The
group of characters should be enclosed inside single quotes or double quotes as:
There is no difference between the single quotes and double quotes while creating the
Strings. Both will work in the same manner.
Length of a String:
Length of a string represents the number of characters in a string. To know the length
of a string, we can use the len() function. This function gives the number of characters
including spaces in the string.
Ex:
Learnvista Pvt Ltd.
2nd Floor, 147, 5th Main Rd, Rajiv Gandhi Nagar HSR Sector 7,Near Salarpuria Serenity, Bengaluru, Karnataka 560102
Mob:- +91 779568798, Email:- [email protected]
Output:
Indexing in Strings:
Index represents the position number. Index is written using square braces [].By specifying
the position number through an index, we can refer to the individual elements of a string.For
example, str[0] refers to the 0th element of the string and
str[1] refers to the 1st element of the string. Thus, str[i| can be used to refer to ith element
of the string. Here, ‘i’ is called the string index because it is specifying the position
number of the element in the string.
When we use index as a negative number, it refers to elements in reverse order. Thus str[-1]
refers to the last element and str[-2] refers to the second element from the last.
If ‘Start’ and ‘stop’ are not specified, then slicing is done from 0th to n-1 th elements. If step size
is not written, then it is taken to be 1.
Ex1:
Output:
Ex2:
Output:
Output:
Ex:
Output:
Concatenation of Strings:
We can use ‘+’ on strings to attach a string at the end of another string. This operator ‘+’
is called addition operator when used on numbers. But, when used on strings, it is called
‘concatenation’ operator since it joins or concatenates the strings.
Output:
Checking membership:
Learnvista Pvt Ltd.
2nd Floor, 147, 5th Main Rd, Rajiv Gandhi Nagar HSR Sector 7,Near Salarpuria Serenity, Bengaluru, Karnataka 560102
Mob:- +91 779568798, Email:- [email protected]
We can check if a string or character is a member of another string or not using ‘in’ and ‘not in’
operators. The ‘in’ operator returns True if the string or character is found in the main string. It
returns False if the string or character is not found in the main String. The ‘not in’ operator
returns False if a string or character is not found in the main string, otherwise True.
The operators ‘in’ and ‘not in’ make case sensitive comparisons. It means these operators,
consider the upper case and lower case letters or strings differently while comparing
strings.
Ex:
Output:
Comparing Strings:
We can use the relational operators like >, >=, <, <=, == or != operators to compare strings.
They return Boolean values, i.e. either True or False depending on the string being compared.
Ex:
Output:
The output will be ‘Name not found’. In this way, spaces may lead to wrong results. Hence
such spaces should be removed from the strings before they are compared. This is
possible using rstrip(), lstrip() and strip() methods. The rstrip() method removes the spaces
which are at the right side of the string. The Istrip() method removes spaces which are at
the left side of the string. strip() method removes spaces from both the sides of the strings.
These methods do not remove spaces which are in the middle of the string. Ex:
Output:
Finding Substrings:
The find(). rfind(), index() and rindex() methods are useful to locate sub strings in a string.These
methods return the location of the first occurrence of the sub string in the main string.The find()
and index() methods search for the sub string from the beginning of the main string.The rfind()
and rindex() methods search for the substring from right to left i.e. in backward order.
This returns an integer number that represents how many times the substring is found in the
main string.We can limit our search by specifying beginning and ending positions in the count()
method so that the substring position is counted only in that range. Hence, the other form of
count() method is:
stringname.replace(old, new)
This will replace all the occurrences of ‘old’ substring with ‘new’ sub string in the main string.
Ex:
Output:
str.split(‘,’)
Observe the comma inside the parentheses. It is called a separator that represents where to
separate or cut the string.
When a group of strings are given, it is possible to join them all and make a single string.
For this purpose, we can use join() method as:
separator. join(str)
where, the ‘separator’ represents the character to be used between the strings in the
output. ‘str’ represents a tuple or list of strings.
Ex:
We want to join the three strings and form a single string. Also, we want to use hyphen
(-) between the three strings in the output. The join() method can be written as:
Output:
Ex:
Output:
When the substring is found in the main string ‘str’, this method returns True. If the string is not
found, it returns False. Similarly to check the ending of a string, we use endswith() method. It
returns True if the string ends with the specified substring, otherwise it returns False.
isalnum() This method returns True if all characters in the string are alphanumeric (A
to Z, a to z, 0 to 9) and there is at least one character otherwise it returns
False.
isalpha() Returns True if the string has at least one character and all
characters are alphabetic (A to Z and a to 2); otherwise, it returns
False.
islower() Returns True if the string contains at least one letter and all
characters are in lower case; otherwise, it returns False.
isupper() Returns True if the string contains at least one letter and all
characters are in upper case; otherwise, it returns False.
istitle() Returns True if each word of the string starts with a capital letter
and there is at least one character in the string; otherwise, it
returns False.
We should first understand the meaning of the first attribute, i.e. format string with
replacement fields’. The replacement fields are denoted by curly braces { } that contain
names or indexes. These names or indexes represent the order of the values. For
example, let’s take an employee details like id number, name and salary in 3 variables
‘id’, ‘name’ and ‘sal’.
We want to create a format string by the name ‘str’ to display these 3 .These 3 values of
variables should be mentioned inside the format() method as format(id,name,sal). The total
format string can be written as:
This string contains 3 replacement fields. The first field {} is replaced by ‘id’ value and the
second field {} is replaced by the ‘name’ value and the third field is replaced by ‘sal’ value.
So, if we display this string using print() method
Output:
To retrieve the 0th character, we can write str[0] and to retrieve the 1st character, we can write
str[1].
Output:
Learnvista Pvt Ltd.
2nd Floor, 147, 5th Main Rd, Rajiv Gandhi Nagar HSR Sector 7,Near Salarpuria Serenity, Bengaluru, Karnataka 560102
Mob:- +91 779568798, Email:- [email protected]
Sorting Strings:
We can sort a group of strings into alphabetical order using the sort() method and sorted()
function.The sort() method is used in the following way:
str.sort()
Here, ‘str’ represents an array that contains a group of strings. When the sort() method is used,
it will sort the original array, i.e. ‘str’. So, the original order of strings will be lost and we will have
only one sorted array. To retain the original array even after sorting, we can use sorted() function
as:
Ex:
Output:
Output:
This for loop repeats once for each character of the string ‘str’. So, if the string has 10
characters, the for loop repeats for 10 times. Hence, by counting the number of repetitions, we
can find the number of characters. This is done by simply incrementing a counting variable ‘i’
inside the loop.
Output:
str1=[]
If n is the position where the sub string to be inserted, we will append the first n-1
characters from str into str1. Then the entire sub string will be appended to str1. In the
final step, we will append the remaining characters (from n till the end) from str to strl.
Thus, the total string will be available in str1 as a list. Figure 8.3 shows the insertion of a
substring in a particular position into a main string.
Since a list contains characters as individual elements, we have to convert the list into a
String format so that we will have a continuous flow of characters. See the difference
between elements of a list and of a string:
[‘H’,’e’,’l’,’l’,’o’,’ ‘,’M’,’y’,’W’,’o’,’r’,’l’,’d’]
Hello MyWorld
Above, the first line represents a list and the second line represents & String, We need the result
in the form of a string, hence we have to convert the list into a String. For this purpose, we can
use join() method with empty string as separator as:
str1=’ ‘.join(str1)
Since the separator is an empty string, the elements of str1 will be joined without gaps in
between and we will have the final string into ‘str1’.
Ex: