Video Illustration
Strings in Python refers to the collection of characters like digits, lower-case alphabets, upper-case alphabets, special letters, etc.
Example of Strings in Python : “Hello”, ‘World 3123’
Generally, A Python String is enclosed under ‘ ‘ (single quotes) or under ” “(double quotes) as shown in above example. Sometimes, we use ”’ (triple quotes) as well, this is to represent a multiline string.
”’ Hello, This is
a multi-line string”’
In Python, keyword str represents a string. We can typecast any of the datatype to string via str().
Like,
num = 10
print("Type before typecasting : ", type(num))
num = str(num)
print("Type after typecasting : ", type(num))
O/P
Type before typecasting : <class ‘int’>
Type after typecasting : <class ‘str’>
When we assign a string value to a Python variable then it is referred to as String object (String Literal).
s = "Hello"
Here, ‘s’ is the string object.
Strings are immutable. Immutable objects are the objects whose content can not be changed.
Length of a Python String
To find the length of a given string we use len() function in Python.
site = "CODE OF GEEKS"
l = len(site)
print(l)
O/P : 13
Here, ‘site’ is the string name whose length is computed using len() function.
Indexing in Python String
Just like arrays, list, set, indexing of string characters also starts with ‘0’.
Consider a sample string site = ‘Code of Geeks’
In the above table, row 1 represents positive indexes, row 2 represents string characters and row 3 represents negative indexes. Python String also supports negative indexing. Like,
site[0] = site[-13] = ‘C’
site[12] = site[-1] = ‘s’
Traversing a Python String
1. Using while loop
site = 'Code of Geeks'
i = 0
while(i < len(site)):
print(site[i], end='')
i+=1
O/P : Code of Geeks
Here, in the above code, we are running a while loop from Index 0 to Index len(site)-1. Also, value at index ‘i’ is accessed as ‘site[i]’.
In Reverse Order
site = 'Code of Geeks'
i = len(site)-1
while(i >= 0):
print(site[i], end='')
i-=1
O/P : skeeG fo edoC
Here, in the above code, we are running a while loop from Index len(site)-1 to 0. Also, value at index ‘i’ is accessed as ‘site[i]’.
2. Using for loop
site = 'Code of Geeks'
for i in range(0, len(site)):
print(site[i], end='')
i+=1
O/P : Code of Geeks
Here, in the above code, we are running a for loop from Index 0 to Index len(site)-1. Also, value at index ‘i’ is accessed as ‘site[i]’.
In Reverse Order
site = 'Code of Geeks'
for i in range(len(site)-1,-1, -1):
print(site[i])
i+=1
O/P : skeeG fo edoC
Here, in the above code, we are running a for loop from Index len(site)-1 to 0 using range() function. Also, value at index ‘i’ is accessed as ‘site[i]’.
3. Using in operator with for loop
site = 'Code of Geeks'
i = 0
for i in site:
print(i, end='')
O/P : Code of Geeks
Here, object ‘i’ stores a character itself, instead of storing an index.
Slicing in Python
Slicing in Python is the process of breaking a string into slices or parts. Typically, Slicing works in the following way :
string_name[start : stop : stepsize]
start : It denotes the starting position where string slicing starts.
stop : It denotes the ending position where string slicing ends.
stepsize : It denotes the number of elements to be skipped. It is optional
By default, slicing is done from 0th to (n-1)th element of a string, keeping stepsize as 1.
string_one = 'CODE OF GEEKS'
string_two = string_one[0 : 9 : 1]
print(string_two)
O/P : CODE OF G
In the code provided, string_one is sliced from 0 to (9-1).
Keeping stepsize as 2 :
In this case, slicing is done from 0th to (n-1)th element of a string, keeping stepsize as 2.
string_one = 'CODE OF GEEKS'
string_two = string_one[0 : 9 : 2]
print(string_two)
O/P : CD FG
In the code provided, string_one is sliced from 0 to (9-1).
We all know, String Slicing is bit complicated, let’s check out some more examples
s = 'CODE OF GEEKS'
print(s[::]) # to access string from 0th to last character, prints 'CODE OF GEEKS'
print(s[::2]) # to access string from 0th to last character in steps of 2, prints 'CD FGES'
print(s[2::]) # to access string from s[2] to last character, prints 'DE OF GEEKS'
print(s[:4:]) # to access string from s[0] to s[3], prints 'CODE'
Also, it is possible to use reverse slicing in order to access string in reverse order. Let’s see few examples for negative slicing as well.
s = 'CODE OF GEEKS'
print(s[::-1]) # to access string in reverse order
print(s[-4:-1]) # to access string from s[-4] to s[-2] from left to right, prints 'EEK'
print(s[-7::]) # to access string from s[-7] to end of the string, prints 'F GEEKS'
When step size is negative, then elements are counted from right to left.
s = 'CODE OF GEEKS'
print(s[-1:-4:-1]) # to access string from s[-1] to s[-3] from right to left, prints 'SKE'
print(s[-3:-7:-1]) # to access string from s[-3] to s[-6] from right to left, prints 'EEG '
Repeating the Strings in Python
We use ‘*’ operator to repeat a string ‘n’ number of times.
s = "py"
print(s*3)
Above code returns ‘pypypy‘ as an output.
You can define any integer value in place of 3.
Concatenation of Strings in Python
Concatenation (in String) is the process of attaching/ appending two or more strings to form a resultant string. We can do it in following ways
1. Using + operator
s1 = "Hello"
s2 = " "
s3 = "Geek"
s4 = s1 + s2 + s3
print("Concatenated String : ", s4)
O/P :
Concatenated String : Hello Geek
Comparing Strings in Python
We can compare two or more strings with the help of relational operators like >, <. >=, <=, ==, or != operators. They return boolean value depending upon the strings that are being compared.
While comparing the strings, Python Interpreter compares them by taking them in English Dictionary order. String that comes first in dictionary will have low value than the string that comes next.
Let us see one example to understand this.
s1 = "India"
s2 = "Bharat"
if s1 == s2:
print("s1 == s2")
elif s1>s2:
print("s1 > s2")
else:
print("s1 < s2")
O/P : s1 > s2
If we check the two strings it is clear that they are not equal also “Bharat” has lower value than “India” when arranged lexicographically. Hence, s1 > s2.
Formatting Strings in Python
Formatting in Strings can be done to refactor or to display a string in a clearer way. We can customize our strings in a dynamic way using String Formatting. It allows us to integrate the values as a part of string that are not defined in the code.
Old school way :
We can use ‘%’ to achieve this.
s = "Baby"
print("Hey, sort me %s " % s)
O/P
Hey, sort me Baby
We can use ‘%d‘ to display integer values.
print("Hey, I am %d " % 10)
O/P
Hey, I am 10
And to print, float values as well
n = 1231.3131313
print('The value of x is %.2f' %n) # 2 decimal places
print('The value of x is %.4f' %n) # 4 decimal places
O/P
The value of x is 1231.31
The value of x is 1231.3131
The newer way… format() function
s1 = 'baby'
s2 = 'fight'
print("Hello {0} wanna {1}".format(s1, s2))
print("Hello {} wanna {}".format(s1, s2))
print('{}{}'.format(s1, s2))
print('{} - {}'.format(s1, s2))
O/P
Hello baby wanna fight
Hello baby wanna fight
babyfight
baby – fight
So, that’s all we have in this lesson. See you in the next..