Python-Unit-II
Python-Unit-II
In this article, we will discuss how to handle exceptions in Python using try, except, and finally statements with the
help of proper examples.
Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors are problems in a program due to
which the program will stop the execution. On the other hand, exceptions are raised when some internal events
occur which change the normal flow of the program.
Syntax error/Compile-Time-Error- is a mistake due to violation of the grammar of language in the program
that prevents it from running/execution. It is detected at compilation time.
Exception/Run-Time-Error - is an abnormal event that occurs during program execution and can be
handled to allow the program to continue running. It is detected at execution/run time.
In Python, there are several built-in exceptions that can be raised when an error occurs during the execution of a
program. Here are some of the most common types of exceptions in Python:
SyntaxError: This exception is raised when the interpreter encounters a syntax error in the code, such as a
misspelled keyword, a missing colon, or an unbalanced parenthesis.
TypeError: This exception is raised when an operation or function is applied to an object of the wrong
type, such as adding a string to an integer.
NameError: This exception is raised when a variable or function name is not found in the current scope.
IndexError: This exception is raised when an index is out of range for a list, tuple, or other sequence types.
KeyError: This exception is raised when a key is not found in a dictionary.
ValueError: This exception is raised when a function or method is called with an invalid argument or
input, such as trying to convert a string to an integer when the string does not represent a valid integer.
AttributeError: This exception is raised when an attribute or method is not found on an object, such as
trying to access a non-existent attribute of a class instance.
IOError: This exception is raised when an I/O operation, such as reading or writing a file, fails due to an
input/output error.
ZeroDivisionError: This exception is raised when an attempt is made to divide a number by zero.
ImportError: This exception is raised when an import statement fails to find or load a module.
These are just a few examples of the many types of exceptions that can occur in Python. It’s important to handle
exceptions properly in your code using try-except blocks or other error-handling techniques, in order to gracefully
handle errors and prevent the program from crashing.
Syntax Error: As the name suggests this error is caused by the wrong syntax in the code. It leads to the termination
of the program.
Example:
Output:
Exceptions: It is a RUN-TIME error and are raised when the program is syntactically correct, but there is a
Semantic (Logical) bug which results in an error and alteres program execution abruptly. This error does not
stop the execution of the program, however, it changes the normal flow of the program.
Example:
Output:
In the above example raised the ZeroDivisionError as we are trying to divide a number by 0.
Note: Exception is the base class for all the exceptions in Python. You can check the exception hierarchy here.
Example:
1) TypeError: This exception is raised when an operation or function is applied to an object of the wrong type.
Here’s an example:
x =5
y = "hello"
z = x + y # Raises a TypeError: unsupported operand type(s) for +: 'int' and
'str'
output:
Traceback (most recent call last):
File "7edfa469-9a3c-4e4d-98f3-5544e60bff4e.py", line 4, in <module>
z = x + y
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Try and except statements are used to catch and handle exceptions in Python. Statements that can raise exceptions
are kept inside the try clause and the statements that handle the exception are written inside except clause.
Example: Let us try to access the array element whose index is out of bound and handle the corresponding
exception.
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
except:
print ("An error occurred")
Output
Second element = 2
An error occurred
In the above example, the statements that can cause the error are placed inside the try statement (second print
statement in our case). The second print statement tries to access the fourth element of the list which is not there and
this throws an exception. This exception is then caught by the except statement.
Catching Specific Exception
A try statement can have more than one except clause, to specify handlers for different exceptions. Please note that
at most one handler will be executed. For example, we can add IndexError in the above code. The general syntax for
adding specific exceptions are –
try:
# statement(s)
except IndexError:
# statement(s)
except ValueError:
# statement(s)
def fun(a):
if a < 4:
try:
fun(3)
fun(5)
The output above is so because as soon as python tries to access the value of b, NameError occurs.
In Python, you can also use the else clause on the try-except block which must be present after all the except clauses.
The code enters the else block only if the try clause does not raise an exception.
Output:
-5.0
a/b result in 0
Python provides a keyword finally, which is always executed after the try and except blocks. The final block always
executes after the normal termination of the try block or after the try block terminates due to some exception.
Syntax:
try:
# Some Code....
except:
# optional block
# Handling of exception (if required)
else:
# execute if no exception
finally:
# Some code .....(always executed)
Example:
# Python program to demonstrate finally
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
Output:
Can't divide by zero
This is always executed
Raising Exception
The raise statement allows the programmer to force a specific exception to occur. The sole argument in raise
indicates the exception to be raised. This must be either an exception instance or an exception class (a class that
derives from Exception).
try:
raise NameError("Hi there") # Raise Error
except NameError:
print ("An exception")
raise # To determine whether the exception was raised or not
The output of the above code will simply line printed as “An exception” but a Runtime error will also occur in the
last due to the raise statement in the last line. So, the output on your command line will look like
Traceback (most recent call last):
File "/home/d6ec14ca595b97bff8d8034bbf212a9f.py", line 5, in <module>
raise NameError("Hi there") # Raise Error
NameError: Hi there
Improved program reliability: By handling exceptions properly, you can prevent your program from
crashing or producing incorrect results due to unexpected errors or input.
Simplified error handling: Exception handling allows you to separate error handling code from the main
program logic, making it easier to read and maintain your code.
Cleaner code: With exception handling, you can avoid using complex conditional statements to check for
errors, leading to cleaner and more readable code.
Easier debugging: When an exception is raised, the Python interpreter prints a traceback that shows the
exact location where the exception occurred, making it easier to debug your code.
Performance overhead: Exception handling can be slower than using conditional statements to check for
errors, as the interpreter has to perform additional work to catch and handle the exception.
Increased code complexity: Exception handling can make your code more complex, especially if you have
to handle multiple types of exceptions or implement complex error handling logic.
Possible security risks: Improperly handled exceptions can potentially reveal sensitive information or
create security vulnerabilities in your code, so it’s important to handle exceptions carefully and avoid
exposing too much information about your program.
Overall, the benefits of exception handling in Python outweigh the drawbacks, but it’s important to use it judiciously
and carefully in order to maintain code quality and program reliability.
Python Functions
The fundamentals of Python functions, including what they are, their syntax, their primary parts, return keywords,
and major types, will be covered in this tutorial. Additionally, we'll examine several instances of Python function
definitions.
A function is a collection of related assertions that performs a mathematical, analytical, or evaluative operation. A
collection of statements called Python Functions returns the particular task. Python functions are simple to define
and essential to intermediate-level programming. The exact criteria hold to function names as they do to variable
names. The goal is to group up certain often performed actions and define a function. We may call the function and
reuse the code contained within it with different variables rather than repeatedly creating the same code block for
different input variables.
User-defined and built-in functions are the two main categories of functions in Python. It helps maintain the
programme concise, unique, and well-structured.
By including functions, we can prevent repeating the same code block repeatedly in a program.
Python functions, once defined, can be called many times and from anywhere in a program.
If our Python program is large, it can be separated into numerous functions which is simple to track.
The key accomplishment of Python functions is we can return as many outputs as we want with different
arguments.
We will define a function that when called will return the square of the number passed to it as an argument.
Code
Output:
Calling a Function
A function is defined by using the def keyword and giving it a name, specifying the arguments that must be passed
to the function, and structuring the code block.
After a function's fundamental framework is complete, we can call it from anywhere in the program. The following
is an example of how to use the a_function function.
Code
Output:
All parameters in the Python programming language are provided by reference. It indicates that if we alter the value
of an argument inside of a function, the calling function will likewise reflect the change. For example,
Code
def value(a,b):
temp = a
a=b
b=temp
def reference(a,b):
temp = a[0]
a[0] = b[0]
b[0] = temp
a, b = 10, 20
value (a, b)
print('SWAPING AFTER CALL BY VALUE makes no change , a = ' , a , ' and b = ', b)
a, b= [10], [20]
reference(a, b)
print('SWAPING AFTER CALL BY REFERENCE makes change , a = ' , a[0] , ' and b = ', b[0])
----output----
Function Arguments
The following are the types of arguments that we can use to call a function:
1. Default arguments
2. Keyword arguments
3. Required arguments
4. Variable-length arguments
1) Default Arguments
A default argument is a kind of parameter that takes as input a default value if no value is supplied for the argument
when the function is called. Default arguments are demonstrated in the following instance.
Code
Output:
2) Keyword Arguments
A function called's arguments are linked to keyword arguments. When invoking a function with keyword arguments,
the user may tell whose parameter value it is by looking at the parameter label.
We can remove certain arguments or arrange them in a different order since the Python interpreter will connect the
provided keywords to link the values with its parameters. Another way to use keywords to invoke the function()
method is as follows:
Code
Output:
3) Required Arguments
The arguments given to a function while calling in a pre-defined positional sequence are required arguments. The
count of required arguments in the method call must be equal to the count of arguments provided while defining the
function.
We must send two arguments to the function function() in the correct order, or it will return a syntax error, as seen
below.
Code
Output:
4) Variable-Length Arguments
We can use special characters in Python functions to pass as many arguments as we want in a function. There are
two types of characters that we can use for this purpose:
Code
Output:
return Statement
We write a return statement in a function to leave a function and give the calculated value when a defined function is
called.
Syntax:
The return statement, which is supplied as output when a particular job or function is finished, might take the form
of an argument, a statement, or a value. A declared function will return a None object if no return statement is
written.
Code
Output:
These types of Python functions are anonymous since we do not declare them, as we declare usual functions, using
the def keyword. We can use the lambda keyword to define the short, single output, anonymous functions.
Lambda expressions can accept an unlimited number of arguments; however, they only return one value as the result
of the function. They can't have numerous expressions or instructions in them. Since lambda needs an expression, an
anonymous function cannot be directly called to print.
Lambda functions contain their unique local domain, meaning they can only reference variables in their argument
list and the global domain name.
Although lambda expressions seem to be a one-line representation of a function, they are not like inline expressions
in C and C++, which pass function stack allocations at execution for efficiency concerns.
Syntax
Code
Output:
The scope of a variable refers to the domain of a program wherever it is declared. A function's arguments and
variables are not accessible outside the defined function. As a result, they only have a local domain.
The lifespan of a variable in RAM is how long it stays there. A function's lifespan is the same as that of its internal
variables. They are taken away after we exit the function. Consequently, a function does not keep the value of a
variable from previous executions.
Code
Output:
Here, we can see that num starts out with a value of 10. The value of num outside of the function remained intact,
even though the function number() changed the value of num to 50.
This is due to the fact that the function's internal variable num is different from the external variable (local to the
function). Despite having the same variable name, they are two separate variables with separate scopes.
Variables beyond the function, on the contrary, are accessible within the function. These variables have a global
reach. We can retrieve their values inside the function but cannot alter or change them. If we declare a variable
global using the keyword global, we can also change the variable's value outside the function.
Functions are considered first-class objects in Python. In a programming language, first-class objects are treated the
same wherever they are used. They can be used in conditional expressions, as arguments, and saved in built-in data
structures. A programming language is considered to implement first-class functions if it treats functions as first-
class objects. The concept of First Class functions is supported by Python.
Inner or nested function refers to a function defined within another defined function. Inner functions can access the
parameters of the outer scope. Inner functions are constructed to cover them from the changes that happen outside
the function. Many developers regard this process as encapsulation.
Code
Output:
In this article, we will discuss the recursion concept in Python. In general, recursion simply means a function that is
defined can call itself. This concept is common in all programming languages and Python; we know that one defined
function can call another function; similarly, a defined function can call itself to loop through the given data until a
certain condition provides the output or stops the loop. But if this recursion process of calling itself is not stopped by
any condition, then the loop will go into an infinity loop, which may sometimes lead to occupy more memory, or the
program never terminates, and there will be no output.
In Python, defining something in terms of itself or a function to call itself or, in simple words executing the same
piece of code again and again for some new values such process is known as recursion. Therefore, we will see how
recursion works where; the recursion function is called by some external piece of code in the program. The recursion
function is a function that calls itself until a certain condition is satisfied. Hence, we should be very careful as
recursion is a very efficient and elegant approach in programming. Still, we have to properly set the condition
criteria; recursion may lead to an infinite loop which can cause a program to never terminate or use excess memory
and processor power.
Now let us demonstrate how the recursive function works with examples as we discussed in the above section.
Example #1
Code:
Output:
In the above program, we can see we have defined a function “rcur_func()” to this function, we are passing an
integer variable “x”, and then we are checking for the condition using “if” statement such as if (x >= 1 ) and if the
condition is satisfied, then it enters the if loop and where it calls the same function again and passes the argument by
decrementing the x value by 1 ( x-1 ). Therefore, in the above program, we have passed the x value as “5” to the
defined function. Now when 5 is given to the “if” statement, then the condition is satisfied and hence the if loop
results “true”, and it enters the loop. Again the same function is called by passing the decremented by 1 x value ( x
=5 -1 ), now the x value is 4 again it will be checked by the “if” statement and the “if” loop condition is satisfied and
results “true” and enters the loop, and again the function is called by passing the decremented by 1 x value ( x= 4 –
1). This process is continued until the if statement condition results false, that means until the x value reaches 1.
Then the output will print the values of the above recursion as 1, 2, 3, 4, 5, as shown in the above screenshot. It will
print only till 5 as the integer value passed to the recursion function is 5, and if we pass integer value 9, then it will
print till 9.
Now let us see what the termination condition in the recursion concept is. In Python, as we discussed above, it is
very important for a recursive function to have a termination condition because if the condition is not specified, then
it may lead to infinite loop recursion, which never terminates the program. Therefore the recursion function needs to
have a termination condition. Now let us take a famous example of finding the factorial of the given number.
So to find the factorial of a given number “z”, we calculate it as z = z * (z -1) until z is greater than 1, we need to
compute this expression, and if z = 0, then the above factorial expression will result in 1. So let us demonstrate
programmatically in the below example.
Example #2
Code:
Output:
In the above program, we can see how we have calculated the factorial of the given number 5, and the result is as
displayed in the above screenshot.
Python String
Till now, we have discussed numbers as the standard data-types in Python. In this section of the tutorial, we will
discuss the most popular data type in Python, i.e., string.
Python string is the collection of the characters surrounded by single quotes, double quotes, or triple quotes. The
computer does not understand the characters; internally, it stores manipulated character as the combination of the 0's
and 1's.`
Each character is encoded in the ASCII or Unicode character. So we can say that Python strings are also called the
collection of Unicode characters.
In Python, strings can be created by enclosing the character or the sequence of characters in the quotes. Python
allows us to use single quotes, double quotes, or triple quotes to create the string.
Syntax:
Here, if we check the type of the variable str using a Python script
In Python, strings are treated as the sequence of characters, which means that Python doesn't support the character
data-type; instead, a single character written as 'p' is treated as the string of length 1.
We can create a string by enclosing the characters in single-quotes or double- quotes. Python also provides triple-
quotes to represent the string, but it is generally used for multiline string or docstrings.
Output:
Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring
Like other languages, the indexing of the Python strings starts from 0. For example, The string "HELLO" is indexed
as given in the below figure. Consider the following example:
1. str = "HELLO"
2. print(str[0])
3. print(str[1])
4. print(str[2])
5. print(str[3])
6. print(str[4])
7. # It returns the IndexError because 6th index doesn't exist
8. print(str[6])
Output:
H
E
L
L
O
IndexError: string index out of range
As shown in Python, the slice operator [] is used to access the individual characters of the string. However, we can
use the : (colon) operator in Python to access the substring from the given string. Consider the following example.
Here, we must notice that the upper range given in the slice operator is always
exclusive i.e., if str = 'HELLO' is given, then str[1:3] will always include
str[1] = 'E', str[2] = 'L' and nothing else.
# Given String
1. str = "JAVATPOINT"
2. # Start Oth index to end
3. print(str[0:])
4. # Starts 1th index to 4th index
5. print(str[1:5])
6. # Starts 2nd index to 3rd index
7. print(str[2:4])
8. # Starts 0th to 2nd index
9. print(str[:3])
10. #Starts 4th to 6th index
11. print(str[4:7])
Output:
JAVATPOINT
AVAT
VA
JAV
TPO
We can do the negative slicing in the string; it starts from the rightmost character, which is indicated as -1. The
second rightmost index indicates -2, and so on. Consider the following image.
1. str = 'JAVATPOINT'
2. print(str[-1])
3. print(str[-3])
4. print(str[-2:])
5. print(str[-4:-1])
6. print(str[-7:-2])
7. # Reversing the given string
8. print(str[::-1])
9. print(str[-12])
Output:
T
I
NT
OIN
ATPOI
TNIOPTAVAJ
IndexError: string index out of range
Reassigning Strings
Updating the content of the strings is as easy as assigning it to a new string. The string object doesn't support item
assignment i.e., A string can only be replaced with new string since its content cannot be partially replaced. Strings
are immutable in Python.
Example 1
1. str = "HELLO"
2. str[0] = "h"
3. print(str)
Output:
However, in example 1, the string str can be assigned completely to a new content as specified in the following
example.
Example 2
1. str = "HELLO"
2. print(str)
3. str = "hello"
4. print(str)
Output:
HELLO
hello
As we know that strings are immutable. We cannot delete or remove the characters from the string. But we can
delete the entire string using the del keyword.
1. str = "JAVATPOINT"
2. del str[1]
Output:
1. str1 = "JAVATPOINT"
2. del str1
3. print(str1)
Output:
NameError: name 'str1' is not defined
String Operators
Operator Description
+ It is known as concatenation operator used to join the strings given either side of the operator.
* It is known as repetition operator. It concatenates the multiple copies of the same string.
[] It is known as slice operator. It is used to access the sub-strings of a particular string.
[:] It is known as range slice operator. It is used to access the characters from the specified range.
in It is known as membership operator. It returns if a particular sub-string is present in the specified string.
It is also a membership operator and does the exact reverse of in. It returns true if a particular substring is not present
not in
in the specified string.
It is used to specify the raw string. Raw strings are used in the cases where we need to print the actual meaning of
r/R escape characters such as "C://python". To define any string as a raw string, the character r or R is followed by the
string.
It is used to perform string formatting. It makes use of the format specifiers used in C programming like %d or %f to
%
map their values in python. We will discuss how formatting is done in python.
Example
Consider the following example to understand the real use of Python operators.
1. str = "Hello"
2. str1 = " world"
3. print(str*3) # prints HelloHelloHello
4. print(str+str1)# prints Hello world
5. print(str[4]) # prints o
6. print(str[2:4]); # prints ll
7. print('w' in str) # prints false as w is not present in str
8. print('wo' not in str1) # prints false as wo is present in str1.
9. print(r'C://python37') # prints C://python37 as it is written
10. print("The string str : %s"%(str)) # prints The string str : Hello
Output:
HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello
Escape Sequence
Let's suppose we need to write the text as - They said, "Hello what's going on?"- the given statement can be written
in single quotes or double quotes but it will raise the SyntaxError as it contains both single and double-quotes.
Example
Consider the following example to understand the real use of Python operators.
Output:
We can use the triple quotes to accomplish this problem but Python provides the escape sequence.
The backslash(/) symbol denotes the escape sequence. The backslash can be followed by a special character and it
interpreted differently. The single quotes inside the string must be escaped. We can apply the same as in the double
quotes.
Example -
1. # using triple quotes
2. print('''''They said, "What's there?"''')
3.
4. # escaping single quotes
5. print('They said, "What\'s going on?"')
6.
7. # escaping double quotes
8. print("They said, \"What's going on?\"")
Output:
They said, "What's there?"
They said, "What's going on?"
They said, "What's going on?"
1. print("C:\\Users\\DEVANSH SHARMA\\Python32\\Lib")
2. print("This is the \n multiline quotes")
3. print("This is \x48\x45\x58 representation")
Output:
C:\Users\DEVANSH SHARMA\Python32\Lib
This is the
multiline quotes
This is HEX representation
We can ignore the escape sequence from the given string by using the raw string. We can do this by writing r or R
in front of the string. Consider the following example.
1. print(r"C:\\Users\\DEVANSH SHARMA\\Python32")
Output:
C:\\Users\\DEVANSH SHARMA\\Python32
The format() method is the most flexible and useful method in formatting strings. The curly braces {} are used as
the placeholder in the string and replaced by the format() method argument. Let's have a look at the given an
example:
Output:
Python allows us to use the format specifiers used in C's printf statement. The format specifiers in Python are treated
in the same way as they are treated in C. However, Python provides an additional operator %, which is used as an
interface between the format specifiers and their values. In other words, we can say that it binds the format specifiers
to the values.
1. Integer = 10;
2. Float = 1.290
3. String = "Devansh"
4. print("Hi I am Integer ... My value is %d\nHi I am float ... My value is %f\nHi I am string ... My value is %
s"%(Integer,Float,String))
Output:
Python provides various in-built functions that are used for string handling. Many String fun
Method Description
capitalize() It capitalizes the first character of the String. This function is deprecated in python3
casefold() It returns a version of s suitable for case-less comparisons.
It returns a space padded string with the original string centred with equal number of left
center(width ,fillchar)
and right spaces.
It counts the number of occurrences of a substring in a String between begin and end
count(string,begin,end)
index.
decode(encoding = 'UTF8', errors =
Decodes the string using codec registered for encoding.
'strict')
encode() Encode S using the codec registered for encoding. Default encoding is 'utf-8'.
endswith(suffix ,begin=0,end=len(stri It returns a Boolean value if the string terminates with given suffix between begin and
ng)) end.
expandtabs(tabsize = 8) It defines tabs in string to multiple spaces. The default space value is 8.
It returns the index value of the string where substring is found between begin index and
find(substring ,beginIndex, endIndex)
end index.
format(value) It returns a formatted version of S, using the passed value.
index(subsring, beginIndex, endIndex) It throws an exception if string is not found. It works same as find() method.
It returns true if the characters in the string are alphanumeric i.e., alphabets or numbers
isalnum()
and there is at least 1 character. Otherwise, it returns false.
It returns true if all the characters are alphabets and there is at least one character,
isalpha()
otherwise False.
isdecimal() It returns true if all the characters of the string are decimals.
It returns true if all the characters are digits and there is at least one character, otherwise
isdigit()
False.
isidentifier() It returns true if the string is the valid identifier.
islower() It returns true if the characters of a string are in lower case, otherwise false.
isnumeric() It returns true if the string contains only numeric characters.
isprintable() It returns true if all the characters of s are printable or s is empty, false otherwise.
isupper() It returns false if characters of a string are in Upper case, otherwise False.
isspace() It returns true if the characters of a string are white-space, otherwise false.
It returns true if the string is titled properly and false otherwise. A title string is the one in
istitle()
which the first character is upper-case whereas the other characters are lower-case.
isupper() It returns true if all the characters of the string(if exists) is true otherwise it returns false.
join(seq) ************ It merges the strings representation of the given sequence.
len(string) It returns the length of a string.
ljust(width[,fillchar]) It returns the space padded strings with the original string left justified to the given width.
lower() It converts all the characters of a string to Lower case.
It removes all leading whitespaces of a string and can also be used to remove particular
lstrip()
character from leading.
It searches for the separator sep in S, and returns the part before it, the separator itself,
partition()
and the part after it. If the separator is not found, return S and two empty strings.
maketrans() It returns a translation table to be used in translate function.
It replaces the old sequence of characters with the new sequence. The max characters are
replace(old,new[,count])
replaced if max is given.
rfind(str,beg=0,end=len(str)) It is similar to find but it traverses the string in backward direction.
rindex(str,beg=0,end=len(str)) It is same as index but it traverses the string in backward direction.
Returns a space padded string having original string right justified to the number of
rjust(width,[,fillchar])
characters specified.
It removes all trailing whitespace of a string and can also be used to remove particular
rstrip()
character from trailing.
It is same as split() but it processes the string from the backward direction. It returns the
rsplit(sep=None, maxsplit = -1) list of words in the string. If Separator is not specified then the string splits according to
the white-space.
Splits the string according to the delimiter str. The string splits according to the space if
split(str,num=string.count(str))
the delimiter is not provided. It returns the list of substring concatenated with the
***************** delimiter.
splitlines(num=string.count('\n')) It returns the list of strings at each line with newline removed.
startswith(str,beg=0,end=len(str)) It returns a Boolean value if the string starts with given str between begin and end.
strip([chars]) It is used to perform lstrip() and rstrip() on the string.
swapcase() It inverts case of all characters in a string.
It is used to convert the string into the title-case i.e., The string meEruT will be converted
title()
to Meerut.
translate(table,deletechars = '') It translates the string according to the translation table passed in the function .
upper() It converts all the characters of a string to Upper Case.
Returns original string leftpadded with zeros to a total of width characters; intended for
zfill(width)
numbers, zfill() retains any sign given (less one zero).
rpartition()
Python program to Split a string based on a delimiter and join the string using another delimiter. Splitting a string
can be quite useful sometimes, especially when you need only certain parts of strings. A simple yet effective
example is splitting the First-name and Last-name of a person. Another application is CSV(Comma Separated Files).
We use split to get data from CSV and join to write data to CSV. In Python, we can use the function split() to split a
string and join() to join a string. For a detailed articles on split() and join() functions, refer these : split() in Python
and join() in Python. Examples :
Below is Python code to Split and Join the string based on a delimiter :
def split_string(string):
return list_string
def join_string(list_string):
return string
# Driver Function
if __name__ == '__main__':
string = 'CMSs for CMSs'
# Splitting a string
list_string = split_string(string)
print(list_string)
Method: In Python, we can use the function split() to split a string and join() to join a string. the split() method in
Python split a string into a list of strings after breaking the given string by the specified separator. Python String
join() method is a string method and returns a string in which the elements of the sequence have been joined by the
str separator.
# Python code
# to split and join given string
# input string
s = 'CMSs for CMSs'
# print the string after split method
print(s.split(" "))
# print the string after join method
print("-".join(s.split()))
Method: Here is an example of using the re module to split a string and a for loop to join the
resulting list of strings:
import re
def split_and_join(string):
# Split the string using a regular expression to match any sequence of non-
alphabetic characters as the delimiter
split_string = re.split(r'[^a-zA-Z]', string)
In the above code, we first imported the re (regular expression) module in order to use the split() function from it.
We then defined a string s which we want to split and join using different delimiters.
To split the string, we used the split() function from the re module and passed it the delimiter that we want to use to
split the string. In this case, we used a space character as the delimiter. This function returns a list of substrings,
where each substring is a part of the original string that was separated by the delimiter.
To join the list of substrings back into a single string, we used a for loop to iterate through the list. For each
substring in the list, we concatenated it to a new string called new_string using the + operator. We also added a
hyphen between each substring, to demonstrate how to use a different delimiter for the join operation.
Finally, we printed both the split and joined versions of the string to the console. The output shows that the string
was successfully split and joined using the specified delimiters.
Here we are finding all the words of the given string as a list (splitting the string based on spaces) using
regex.findall() method and joining the result to get the result with hyphen
# Python code
# to split and join given string
import re
# input string
s = 'CMSs for CMSs'
# print the string after split method
print(re.findall(r'[a-zA-Z]+', s))
# print the string after join method
print("-".join(re.findall(r'[a-zA-Z]+', s)))
Output
['CMSs', 'for', 'CMSs']
CMSs-for-CMSs
Raw String and Unicode String in Python
Raw string literals in Python define normal strings that are prefixed with either an r or R before the
opening quote. If a backslash ( \) is in the string, the raw string treats this character as a literal character
but not an escape character.
For example,
print(r'\n')
print(r'\t')
Output:
\n
\t
It is required to double every backslash when defining a string so that it is not mistaken as the beginning
of an escape sequence like a new-line, or the new-tab. We see such syntax application in the syntax of
regular expressions and when expressing Windows file paths.
r'\' will raise a syntax error because r treats the backslash as a literal. Without the r prefix, the backslash is
treated as an escape character.
Example:
text="Hello\nWorld"
print(text)
Output:
Hello
World
Without the raw string flag r, the backslash is treated as an escape character, so when the above string is
printed, the new line escape sequence is generated. Hence the two strings in the text are printed out on
separate lines, as displayed in the output.
Using the same text example, add the r prefix before the string.
Example:
text=r"Hello\nWorld"
print(text)
Output:
Hello\nWorld
From the output, the raw string flag treats the backslash as a literal and prints out the text with
the backslash included. So, the input and output are both the same because the backslash
character is not escaped.
print('\\n')
print(r'\n')
Unicode is one way of storing python strings. Unicode can store strings from all language types.
The second way is the ASCII type of string storage represented as str in Python. str is the
default data type to store strings in Python.
To convert a string to Unicode type, put a u before the text like this - u'string' or call the
unicode() function like this - unicode('string').
u'text' is a Unicode string while text is a byte string. A Unicode object takes more memory
space.
----------------------------------------------------------------------------------------------------------------------------------------------- \][p8