Understanding Strings in Python
Understanding Strings in Python
In python, anything that you enclose between single or double quotation marks is considered a
string. A string is essentially a sequence or array of textual data. Strings are used when working with
Unicode characters.
Example
name = "Harry"
Output
Hello, Harry
Note: It does not matter whether you enclose your strings in single or double quotes, the output
remains the same.
Sometimes, the user might need to put quotation marks in between the strings. Example, consider
the sentence: He said, “I want to eat an apple”.
How will you print this statement in python?: He said, "I want to eat an apple". We will definitely use
single quotes for our convenience
Multiline Strings
If our string has multiple lines, we can create them like this:
print(a)
print(name[0])
print(name[1])
print(character)
Above code prints all the characters in the string name one by one!
Length of a String
Example:
fruit = "Mango"
len1 = len(fruit)
Output:
String as an array
A string is essentially a sequence of characters also called an array. Thus we can access the elements
of this array.
Example:
pie = "ApplePie"
print(pie[:5])
Output:
Apple
Note: This method of specifying the start and end index to specify a part of a string is called slicing.
Slicing Example:
pie = "ApplePie"
Output:
Apple
Pie
pleP
ApplePie
Strings are arrays and arrays are iterable. Thus we can loop through strings.
Example:
alphabets = "ABCDE"
for i in alphabets:
print(i)
Output:
String methods
Python provides a set of built-in methods that we can use to alter and modify the strings.
upper() :
Example:
str1 = "AbcDEfghIJ"
print([Link]())
Output:
ABCDEFGHIJ
lower()
Example:
str1 = "AbcDEfghIJ"
print([Link]())
Output:
abcdefghij
strip() :
The strip() method removes any white spaces before and after the string.
Example:
print([Link])
Output:
Silver Spoon
rstrip() :
print([Link]("!"))
Output:
Hello
replace() :
The replace() method replaces all occurences of a string with another string. Example:
print([Link]("Sp", "M"))
Output:
Silver Moon
split() :
The split() method splits the given string at the specified instance and returns the separated strings
as list items.
Example:
Output:
['Silver', 'Spoon']
There are various other string methods that we can use to modify our strings.
capitalize() :
The capitalize() method turns only the first character of the string to uppercase and the rest other
characters of the string are turned to lowercase. The string has no effect if the first character is
already uppercase.
Example:
str1 = "hello"
capStr1 = [Link]()
print(capStr1)
capStr2 = [Link]()
print(capStr2)
Output:
Hello
Hello world
center() :
The center() method aligns the string to the center as per the parameters given by the user.
Example:
print([Link](50))
Output:
We can also provide padding character. It will fill the rest of the fill characters provided by the user.
Example:
print([Link](50, "."))
Output:
count() :
The count() method returns the number of times the given value has occurred within the given
string.
Example:
str2 = "Abracadabra"
countStr = [Link]("a")
print(countStr)
Output:
endswith() :
The endswith() method checks if the string ends with a given value. If yes then return True, else
return False.
Example :
print([Link]("!!!"))
Output:
True
We can even also check for a value in-between the string by providing start and end index positions.
Example:
print([Link]("to", 4, 10))
Output:
True
find() :
The find() method searches for the first occurrence of the given value and returns the index where it
is present. If given value is absent from the string then return -1.
Example:
print([Link]("is"))
Output:
10
As we can see, this method is somewhat similar to the index() method. The major difference being
that index() raises an exception if value is absent whereas find() does not.
Example:
print([Link]("Daniel"))
Output:
-1
index() :
The index() method searches for the first occurrence of the given value and returns the index where
it is present. If given value is absent from the string then raise an exception.
Example:
print([Link]("Dan"))
Output:
13
As we can see, this method is somewhat similar to the find() method. The major difference being
that index() raises an exception if value is absent whereas find() does not.
Example:
print([Link]("Daniel"))
Output:
isalnum() :
The isalnum() method returns True only if the entire string only consists of A-Z, a-z, 0-9. If any other
characters or punctuations are present, then it returns False.
Example 1:
str1 = "WelcomeToTheConsole"
print([Link]())
Output:
True
isalpha() :
The isalnum() method returns True only if the entire string only consists of A-Z, a-z. If any other
characters or punctuations or numbers(0-9) are present, then it returns False.
Example :
str1 = "Welcome"
print([Link]())
Output:
True
islower() :
The islower() method returns True if all the characters in the string are lower case, else it returns
False.
Example:
print([Link]())
Output:
True
isprintable() :
The isprintable() method returns True if all the values within the given string are printable, if not,
then return False.
Example :
print([Link]())
Output:
True
isspace() :
The isspace() method returns True only and only if the string contains white spaces, else returns
False.
Example:
print([Link]())
print([Link]())
Output:
True
True
istitle() :
The istitile() returns True only if the first letter of each word of the string is capitalized, else it returns
False.
Example:
print([Link]())
Output:
True
Example:
print([Link]())
Output:
False
isupper() :
The isupper() method returns True if all the characters in the string are upper case, else it returns
False.
Example :
print([Link]())
Output:
True
startswith() :
The endswith() method checks if the string starts with a given value. If yes then return True, else
return False.
Example :
print([Link]("Python"))
Output:
True
swapcase() :
The swapcase() method changes the character casing of the string. Upper case are converted to
lower case and lower case to upper case.
Example:
print([Link]())
Output:
title() :
The title() method capitalizes each letter of the word within the string.
Example:
print([Link]())
Output:
if-else Statements
Sometimes the programmer needs to check the evaluation of certain expression(s), whether the
expression(s) evaluate to True or False. If the expression evaluates to False, then the program
execution follows a different path than it would have if the expression had evaluated to True.
Based on this, the conditional statements are further classified into following types:
if
if-else
if-else-elif
nested if-else-elif.
Execute the block of code inside if statement. After execution return to the code out of the if……else
block.\
Example:
applePrice = 210
budget = 200
else:
Output:
elif Statements
Sometimes, the programmer may want to evaluate more than one condition, this can be done using
an elif statement.
Execute the block of code inside if statement if the initial expression evaluates to True. After
execution return to the code out of the if block.
Execute the block of code inside the first elif statement if the expression inside it evaluates True.
After execution return to the code out of the if block.
Execute the block of code inside the second elif statement if the expression inside it evaluates True.
After execution return to the code out of the if block.
Execute the block of code inside the nth elif statement if the expression inside it evaluates True.
After execution return to the code out of the if block.
Execute the block of code inside else statement if none of the expression evaluates to True. After
execution return to the code out of the if block.
Example:
num = 0
print("Number is negative.")
print("Number is Zero.")
else:
print("Number is positive.")
Output:
Number is Zero.
Nested if statements
We can use if, if-else, elif statements inside other if statements as well.
Example:
num = 18
print("Number is negative.")
else:
else:
print("Number is zero")
Output:
To implement switch-case like characteristics very similar to if-else functionality, we use a match
case in python. If you are coming from a C, C++ or Java like language, you must have heard of switch-
case statements. If this is your first language, dont worry as I will tell you everything you need to
know about match case statements in this video!
A match statement will compare a given variable’s value to different shapes, also referred to as the
pattern. The main idea is to keep on comparing the variable with all the present patterns until it fits
into one.
The case clause consists of a pattern to be matched to the variable, a condition to be evaluated if the
pattern matches, and a set of statements to be executed if the pattern matches.
Syntax:
match variable_name:
Example:
x=4
# if x is 0
case 0:
print("x is zero")
case 4 if x % 2 == 0:
# default case(will only be matched if the above cases were not matched)
case _:
print(x)
Output:
x % 2 == 0 and case is 4
Introduction to Loops
Sometimes a programmer wants to execute a group of statements a certain number of times. This
can be done using loops. Based on this loops are further classified into following main types;
for loop
while loop
for loops can iterate over a sequence of iterable objects in python. Iterating over a sequence is
nothing but iterating over strings, lists, tuples, sets and dictionaries.
name = 'Abhishek'
for i in name:
A, b, h, i, s, h, e, k,
for x in colors:
print(x)
Output:
Red
Green
Blue
Yellow
range():
What if we do not want to iterate over a sequence? What if we want to use for loop for a specific
number of times?
Example:
for k in range(5):
print(k)
Output:
2
3
Here, we can see that the loop starts from 0 by default and increments at each iteration.
Example:
for k in range(4,9):
print(k)
Output:
Quick Quiz
As the name suggests, while loops execute statements while the condition is True. As soon as the
condition becomes False, the interpreter comes out of the while loop.
Example:
count = 5
print(count)
count = count - 1
Output:
5
Here, the count variable is set to 5 which decrements after each iteration. Depending upon the while
loop condition, we need to either increment or decrement the counter variable (the variable count,
in our case) or the loop will continue forever.
We can even use the else statement with the while loop. Essentially what the else statement does is
that as soon as the while loop condition becomes False, the interpreter comes out of the while loop
and the else statement is executed.
Example:
x=5
print(x)
x=x-1
else:
print('counter is 0')
Output:
counter is 0
To create a do while loop in Python, you need to modify the while loop a bit in order to get similar
behavior to a do while loop.
The most common technique to emulate a do-while loop in Python is to use an infinite while loop
with a break statement wrapped in an if statement that checks a given condition and breaks the
iteration if that condition becomes true:
Example
while True:
print(number)
break
Output
-1
Explanation
This loop uses True as its formal condition. This trick turns the loop into an infinite loop. Before the
conditional statement, the loop runs all the required processing and updates the breaking condition.
If this condition evaluates to true, then the break statement breaks out of the loop, and the program
execution continues its normal path.
break statement
The break statement enables a program to skip over a part of the code. A break statement
terminates the very loop it lies within.
example
for i in range(1,101,1):
if(i==50):
break
else:
print("Mississippi")
print("Thank you")
output
1 Mississippi
2 Mississippi
3 Mississippi
4 Mississippi
5 Mississippi
50 Mississippi
Continue Statement
The continue statement skips the rest of the loop statements and causes the next iteration to occur.
example
for i in [2,3,4,6,8,0]:
if (i%2!=0):
continue
print(i)
output
Python Functions
A function is a block of code that performs a specific task whenever it is called. In bigger programs,
where we have large amounts of code, it is advisable to create or use existing functions that make
the program flow organized and neat.
Built-in functions
User-defined functions
Built-in functions:
These functions are defined and pre-coded in python. Some examples of built-in functions are as
follows:
min(), max(), len(), sum(), type(), range(), dict(), list(), tuple(), set(), print(), etc.
User-defined functions:
We can create functions to perform specific tasks as per our needs. Such functions are called user-
defined functions.
Syntax:
def function_name(parameters):
pass
Any statements and other code within the function should be indented.
Calling a function:
We call a function by giving the function name, followed by parameters (if any) in the parenthesis.
Example:
name("Sam", "Wilson")
Output:
Default Arguments
Keyword Arguments
Required Arguments
Default arguments:
We can provide a default value while creating a function. This way the function assumes a default
value even if a value is not provided in the function call for that argument.
Example:
Output:
Keyword arguments:
We can provide arguments with key = value, this way the interpreter recognizes the arguments by
the parameter name. Hence, the the order in which the arguments are passed does not matter.
Example:
Output:
Required arguments:
In case we don’t pass the arguments with a key = value syntax, then it is necessary to pass the
arguments in the correct positional order and the number of arguments passed should match with
actual function definition.
Example 1: when number of arguments passed does not match to the actual function definition.
name("Peter", "Quill")
Output:
name("Peter", "Quill")\
Example 2: when number of arguments passed matches to the actual function definition.
Output:
Variable-length arguments:
Sometimes we may need to pass more arguments than those defined in the actual function. This can
be done using variable-length arguments.
Arbitrary Arguments:
While creating a function, pass a * before the parameter name while defining the function. The
function accesses the arguments by processing them in the form of tuple.
Example:
def name(*name):
Output:
Hello, James Buchanan Barnes
While creating a function, pass a * before the parameter name while defining the function. The
function accesses the arguments by processing them in the form of dictionary.
Example:
def name(**name):
Output:
return Statement
The return statement is used to return the value of the expression back to the calling function.
Example:
return "Hello, " + fname + " " + mname + " " + lname
Output:
Python Lists
List items are separated by commas and enclosed within square brackets [].
Example 1:
lst1 = [1,2,2,3,5,4,6]
print(lst1)
print(lst2)
Output:
[1, 2, 2, 3, 5, 4, 6]
Example 2:
print(details)
Output:
As we can see, a single list can contain items of different data types.
List Index
Each item/element in a list has its own unique index. This index can be used to access any particular
item from the list. The first item has index [0], second item has index [1], third item has index [2] and
so on.
Example:
We can access list items by using its index with the square bracket syntax []. For example colors[0]
will give "Red", colors[1] will give "Green" and so on...
Positive Indexing:
As we have seen that list items have index, as such we can access items using these indexes.
Example:
print(colors[2])
print(colors[4])
print(colors[0])
Output:
Blue
Green
Red
Negative Indexing:
Similar to positive indexing, negative indexing is also used to access items, but from the end of the
list. The last item has index [-1], second last item has index [-2], third last item has index [-3] and so
on.
Example:
print(colors[-1])
print(colors[-3])
print(colors[-5])
Output:
Green
Blue
Red
We can check if a given item is present in the list. This is done using the in keyword.
if "Yellow" in colors:
print("Yellow is present.")
else:
print("Yellow is absent.")
Output:
Yellow is present.
if "Orange" in colors:
print("Orange is present.")
else:
print("Orange is absent.")
Output:
Orange is absent.
Range of Index:
You can print a range of list items by specifying where you want to start, where do you want to end
and if you want to skip elements in between the range.
Syntax:
animals = ["cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow"]
Output:
Here, we provide index of the element from where we want to start and the index of the element till
which we want to print the values.
Note: The element of the end index provided will not be included.
Example: printing all element from a given index till the end
animals = ["cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow"]
Output:
animals = ["cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow"]
Output:
When no start index is provided, the interpreter prints all the values from start up to the end index
provided.
animals = ["cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow"]
Output:
Here, we have not provided start and index, which means all the values will be considered. But as we
have provided a jump index of 2 only alternate values will be printed.
animals = ["cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow"]
print(animals[Link])
Output:
List Comprehension
List comprehensions are used for creating new lists from other iterables like lists, tuples,
dictionaries, sets, and even in arrays and strings.
Syntax:
Iterable: It can be list, tuples, dictionaries, sets, and even in arrays and strings.
Condition: Condition checks if the item should be added to the new list or not.
Example 1: Accepts items with the small letter “o” in the new list
print(namesWith_O)
Output:
print(namesWith_O)
Output:
['Sarah', 'Bruno', 'Anastasia']
List Methods
[Link]()
This method sorts the list in ascending order. The original list is updated
Example 1:
[Link]()
print(colors)
num = [4,2,5,3,6,1,2,1,2,8,9,7]
[Link]()
print(num)
Output:
[1, 1, 2, 2, 2, 3, 4, 5, 6, 7, 8, 9]
Example:
[Link](reverse=True)
print(colors)
num = [4,2,5,3,6,1,2,1,2,8,9,7]
[Link](reverse=True)
print(num)
Output:
['voilet', 'indigo', 'green', 'blue']
[9, 8, 7, 6, 5, 4, 3, 2, 2, 2, 1, 1]
Note: Do not mistake the reverse parameter with the reverse method.
reverse()
Example:
[Link]()
print(colors)
num = [4,2,5,3,6,1,2,1,2,8,9,7]
[Link]()
print(num)
Output:
[7, 9, 8, 2, 1, 2, 1, 6, 3, 5, 2, 4]
index()
This method returns the index of the first occurrence of the list item.
Example:
print([Link]("green"))
num = [4,2,5,3,6,1,2,1,3,2,8,9,7]
print([Link](3))
Output:
count()
Returns the count of the number of items with the given value.
Example:
print([Link]("green"))
num = [4,2,5,3,6,1,2,1,3,2,8,9,7]
Output:
copy()
Returns copy of the list. This can be done to perform operations on the list without modifying the
original list.
Example:
newlist = [Link]()
print(colors)
print(newlist)
Output:
Example:
[Link]("green")
print(colors)
Output:
insert():
This method inserts an item at the given index. User has to specify index and the item to be inserted
within the insert() method.
Example:
print(colors)
Output:
extend():
This method adds an entire list or any other collection datatype (set, tuple, dictionary) to the existing
list.
Example 1:
[Link](rainbow)
print(colors)
Output:
Example:
print(colors + colors2)
Output:
Python Tuples
Tuples are ordered collection of data items. They store multiple items in a single variable. Tuple
items are separated by commas and enclosed within round brackets (). Tuples are unchangeable
meaning we can not alter them after creation.
Example 1:
tuple1 = (1,2,2,3,5,4,6)
print(tuple1)
print(tuple2)
Output:
(1, 2, 2, 3, 5, 4, 6)
('Red', 'Green', 'Blue')
Example 2:
print(details)
Output:
Tuple Indexes
Each item/element in a tuple has its own unique index. This index can be used to access any
particular item from the tuple. The first item has index [0], second item has index [1], third item has
index [2] and so on.
Example:
I. Positive Indexing:
As we have seen that tuple items have index, as such we can access items using these indexes.
Example:
print(country[0])
print(country[1])
print(country[2])
Output:
Spain
Italy
India
Similar to positive indexing, negative indexing is also used to access items, but from the end of the
tuple. The last item has index [-1], second last item has index [-2], third last item has index [-3] and
so on.
Example:
print(country[-3])
print(country[-4])
Output:
Germany
India
Italy
We can check if a given item is present in the tuple. This is done using the in keyword.
Example 1:
if "Germany" in country:
print("Germany is present.")
else:
print("Germany is absent.")
Output:
Germany is present.
Example 2:
if "Russia" in country:
print("Russia is present.")
else:
print("Russia is absent.")
Output:
Russia is absent.
You can print a range of tuple items by specifying where do you want to start, where do you want to
end and if you want to skip elements in between the range.
Syntax:
animals = ("cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow")
Output:
Example: Printing all element from a given index till the end
animals = ("cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow")
Output:
When no end index is provided, the interpreter prints all the values till the end.
animals = ("cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow")
Output:
When no start index is provided, the interpreter prints all the values from start up to the end index
provided.
animals = ("cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow")
Here, we have not provided start and end index, which means all the values will be considered. But
as we have provided a jump index of 2 only alternate values will be printed.
animals = ("cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow")
print(animals[Link])
Output:
Here, jump index is 3. Hence it prints every 3rd element within given index.
Manipulating Tuples
Tuples are immutable, hence if you want to add, remove or change tuple items, then first you must
convert the tuple to a list. Then perform operation on that list and convert it back to tuple.
Example:
temp = list(countries)
countries = tuple(temp)
print(countries)
Output:
However, we can directly concatenate two tuples without converting them to list.
Example:
print(southEastAsia)
Output:
Tuple methods
As tuple is immutable type of collection of elements it have limited built in [Link] are
explained below
count() Method
The count() method of Tuple returns the number of times the given element appears in the tuple.
Syntax:
[Link](element)
Example
Tuple1 = (0, 1, 2, 3, 2, 3, 1, 3, 2)
res = [Link](3)
Output
3
index() method
The Index() method returns the first occurrence of the given element from the tuple.
Syntax:
Note: This method raises a ValueError if the element is not found in the tuple.
Example
Tuple = (0, 1, 2, 3, 2, 3, 1, 3, 2)
res = [Link](3)
Output
print([Link](price = 49))
f-strings in python
It is a new string formatting mechanism introduced by the PEP 498. It is also known as Literal String
Interpolation or more commonly as F-strings (f character preceding the string literal). The primary
focus of this mechanism is to make the interpolation easier.
When we prefix the string with the letter 'f', the string becomes the f-string itself. The f-string can be
formatted in much same as the [Link]() method. The f-string offers a convenient way to embed
Python expression inside string literals for formatting.
Example
val = 'Geeks'
name = 'Tushar'
age = 23
Output:
In the above code, we have used the f-string to format the string. It evaluates at runtime; we can put
all valid Python expressions in them.
Example
print(f"{2 * 30})"
Output:
60
Docstrings in python
Python docstrings are the string literals that appear right after the definition of a function, method,
class, or module.
Example
def square(n):
print(n**2)
square(5)
Here,
'''Takes in a number n, returns the square of n''' is a docstring which will not appear in output
Output:
25
"""
This function simply wraps the ``+`` operator, and does not
Parameters
----------
num1 : int
num2 : int
Returns
-------
int
See Also
--------
Examples
--------
>>> add(2, 2)
>>> add(25, 0)
25
"""
Python Comments
Comments are descriptions that help programmers better understand the intent and functionality of
the program. They are completely ignored by the Python interpreter.
Python docstrings
As mentioned above, Python docstrings are strings used right after the definition of a function,
method, class, or module (like in Example 1). They are used to document our code.
Whenever string literals are present just after the definition of a function, module, class or method,
they are associated with the object as their doc attribute. We can later use this attribute to retrieve
this docstring.
Example
def square(n):
return n**2
print(square.__doc__)
Output: