0% found this document useful (0 votes)
16 views

Python Programming Pritam Chakraborty

Uploaded by

cookieswarna
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Python Programming Pritam Chakraborty

Uploaded by

cookieswarna
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 112

Python Programming

BCAAE301

Asst. Prof. Pritam Chakraborty


Department of Computer Application and Science
Institute of Engineering & Management (Ashram Campus)

Copyright @Pritam_Chakraborty
• What is Python?

Python is an interpreted, object-oriented, high-level programming


language with dynamic semantics. Its high-level built in data
structures, combined with dynamic typing and dynamic binding, make
it very attractive for Rapid Application Development, as well as for use
as a scripting or glue language to connect existing components
together.

Dynamic Semantics: In Python, dynamic semantics means that


variables are dynamic objects. This is because Python is a high-level
language, and unlike low-level languages like C, it does not require you
to statically define the type of a variable. Dynamic objects are allowed
to change as the program runs.

Copyright @Pritam_Chakraborty
Programing Language Trends:
For the Year : 2023-24

Copyright @Pritam_Chakraborty
Why Do People are getting Crazy over Python ?

Copyright @Pritam_Chakraborty
• an open-source, high-level, interpreted, general-purpose, dynamic
programming language

• relatively easy to pick up and use.

• Extensive libraries are available

Copyright @Pritam_Chakraborty
• flexibility as a programming language means it can also be used as an
add-on to make highly customizable programs.

• Cross-platform language

• Software quality.

• Python data types are strongly and dynamically typed.

Copyright @Pritam_Chakraborty
• embedded easily into any application to provide a programmable
interface.

• Developer productivity.

• Python’s rapid edit-test-debug cycle and lack of a compilation step


make development and debugging much more efficient.

Copyright @Pritam_Chakraborty
Copyright @Pritam_Chakraborty
Copyright @Pritam_Chakraborty
Limitations of Python

• Speed is an issue. As Python is an interpreted language, it is slower


than compiled languages.

• Design restrictions. The dynamically typed language comes with


errors only at runtime; Python’s global interpreter lock and whitespace
are a few design issues.

Copyright @Pritam_Chakraborty
Python Features From Other Programing
Languages
• Function Concept from C Language
• Object Oriented Feature from C++ Language
• Scripting feature from PEARL and Shell Script
• Modular programming features from Modula-3
• Syntax from C Language and ABC Language

Copyright @Pritam_Chakraborty
Compiler Versus Interpreter

The Process of Creating a Computer Program

Copyright @Pritam_Chakraborty
• Compiler meticulously scans and converts the source code before
launching the program. In this perspective, the high-level program is called
the source code, and the translated program is called the object code or the
executable. Compiling a program allows users to run it repeatedly without
retranslating it each time. A hardware executor can then run the compiled
object code.

Copyright @Pritam_Chakraborty
Structure of a Compiler

Copyright @Pritam_Chakraborty
High-Level Block diagram of an Interpreter

Copyright @Pritam_Chakraborty
Python Interpreter

Copyright @Pritam_Chakraborty
Copyright @Pritam_Chakraborty
Copyright @Pritam_Chakraborty
IDE’s and Code Editors
• What Is an IDE?

An IDE enables programmers to combine the different aspects of


writing a computer program.
IDEs increase programmer productivity by introducing features like
editing source code, building executables, and debugging.

Copyright @Pritam_Chakraborty
• What is a Code Editors?

Code editor is an optimized text editor that focuses on coding.

Copyright @Pritam_Chakraborty
Top IDEs For Python
• IDLE: IDLE (Integrated Development and Learning Environment) is a
default editor that accompanies Python

• PyCharm: This IDE is suitable for professional developers and


facilitates the development of large Python projects.
Pricing: FREE

• Visual Studio Code

Copyright @Pritam_Chakraborty
• Sub Lime Text 3

• Atom: Atom is an open-source code editor by GitHub and supports


Python development

• Jupyter: Jupyter is widely used in the field of data science.


It is easy to use, interactive and allows live code sharing and
visualization.

• Spyder

Copyright @Pritam_Chakraborty
• PyDev

• Thonny

• Wing

• Vim

• Pyscripter

• Rodeo

Copyright @Pritam_Chakraborty
Installing Python
• Installing Python on Windows/Mac
• Step 1: Go to https://www.python.org/  Dowloads

Copyright @Pritam_Chakraborty
• Integrate Python in VSCode

Step1: Install a Python interpreter  https://www.python.org/

Step2: Start VS Code in a workspace folder

Step3: Create a virtual environment

Step4: Create a Python source code file

Copyright @Pritam_Chakraborty
• Step3: Create a virtual environment

A best practice for Python Developer is to use Project Specific Virtual


Environment.

Open Command Pallete: ( Ctrl + Shift + p) tart typing the Python:


Create Environment command to search, and then select the
command.

Copyright @Pritam_Chakraborty
• The command then presents a list of interpreters that can be used for
your project. Select the interpreter you installed at the beginning of
the tutorial.

Copyright @Pritam_Chakraborty
• After Selecting the Interpreter a notification will show the progress of
the environment creation and the environment folder (/.venv) will
appear in your workspace.

Copyright @Pritam_Chakraborty
• Ensure your new environment is selected by using the Python: Select
Interpreter command from the Command Palette.

Copyright @Pritam_Chakraborty
Create a Python source code file

Copyright @Pritam_Chakraborty
Copyright @Pritam_Chakraborty
Run Python code

Copyright @Pritam_Chakraborty
Configure and run the debugger

Copyright @Pritam_Chakraborty
Let’s Start Coding in Python

Copyright @Pritam_Chakraborty
Elements of Python Language
• The set of valid characters that a programming language can recognize is called the character set
of the language. Two types of character sets are
• Source Characters. ( Alphabets uppercase and lowercase, underscore, Special characters blank –
(+,-,*,/,^,~,%,!,&,|,(),{},[] ?’, ;, \), blank(“”))
• The Token is the smallest lexical unit in a program. The Types of tokens are listed below.

1. Identifiers
2. Keywords
3. Literals
4. Punctuations

Copyright @Pritam_Chakraborty
Identifiers

• Identifiers- In Python, all variables, objects, and functions are given a


name. These names are called identifiers.
• Certain rules govern how a name can be given. The guidelines are
given below.
1) Every identifier must start with a letter or underscore ("_")
2) The letter or underscore can be followed by any sequence of letters,
digits, or underscores.
3) Identifier cannot have a space
4) Identifiers are space sensitive. So the names celsius, Celsius, and
CELSIUS are different

Copyright @Pritam_Chakraborty
Keywords
• Python has many inbuilt functions like input(). So Python does not
allow a program to use these function names liberally.
Keywords in Python:

and as assert del for False break class finally is

return None continue def del else if in global not

local except in raise with or else import True Float

Copyright @Pritam_Chakraborty
Literals
• Literal is one way of specifying data values. These will be the values
that never modify while the program is executing.
• Literals in Python are numbers, text, or other fixed data, unlike
variables whose values change during the action.
• Some of the literals are listed below:
1. String literals
2. Numerical literals
3. Boolean literals

Copyright @Pritam_Chakraborty
• String Literals • Numerical Literals
>>> # string literals Example of handling constant as a variable
>>> # in single quote
>>> single_quote = ‘stringliterals’
>>> # in double quotes >>>
>>> double_quotes = "stringliterals" >>> PI = 3.14
>>> # multi-line string
>>> TEMPERATURE = 9.0
>>> multiline = ‘’’ string
... literals’’’
>>> print(single_quote)
stringliterals
>>> print(double_quotes)
stringliterals
>>> print(multiline)
string
literals
>>>

Copyright @Pritam_Chakraborty
Python Code Block Structure

Copyright @Pritam_Chakraborty
Illustration of Blocks in Python
x = 10 # Block 1 starts
if x% 2 == 0: # Block 1 continues
print("The number is even" ) # Block 2
else: # Block 1
print("The number is odd") # Block 2
print("Program Ends’) # Block 1 continues

Copyright @Pritam_Chakraborty
Comments in Python
Block Comments illustration Inline comments illustration Multiple quotes illustration

>>> # This is a single-line comment >>> a = 10 # a is initialized to 10 >>> # Multiline Quote


>>> # This is a block comment >>> a = 10 # a is initialized to 10 >>> """
>>> # This is a block comment >>> b = 10 # b is initialized to 10 ... This is a multiline quote
>>> c = a + b # c = a + b ... using Triple quotes
>>> ... """
>>>

Copyright @Pritam_Chakraborty
Variables and Assignment Statement
• In Python everything is an object, therefore a variable also is an
object. Thus, the rules for forming a variable are the same as the
identifiers.

Copyright @Pritam_Chakraborty
Assignment Statement
• One of the most critical statements in Python is the assignment
statement. The syntax of the introductory assignment statement is
given as follows:

• An alternative form of an assignment statement is to assign/compute


several values simultaneously. The syntax of simultaneous is given as
follows:

Copyright @Pritam_Chakraborty
Name Spaces
• Python interpreter uses a unique structure called namespace using
which it maintains a list of names and their associated values.
• Python updates the list when a new variable is created and it is
deleted in the namespace when the variable is deleted.

Copyright @Pritam_Chakraborty
Example 1: Scope and Namespace in Python
# global_var is in the global namespace
global_var = 10

def outer_function():
# outer_var is in the local namespace
outer_var = 20
•global_var - is in the global
def inner_function(): namespace with value 10
# inner_var is in the nested local namespace
inner_var = 30 •outer_val - is in the local

print(inner_var)
namespace
of outer_function() with value 20
print(outer_var)
•inner_val - is in the nested local
inner_function() namespace
# print the value of the global variable of inner_function() with value 30
print(global_var)

# call the outer function and print local and nested local variables
Copyright @Pritam_Chakraborty
outer_function()
Example 2: Use of global Keyword in Python

# define global variable


global_var = 10
when the function is called, the global keyword is used to
def my_function(): indicate that global_var is a global variable, and its value
# define local variable is modified to 30.
local_var = 20 So, when the code is executed, global_var is printed first
with a value of 10, then the function is called and the
# modify global variable value global variable is modified to 30 from the inside of the
global global_var function.
global_var = 30 And finally the modified value of global_var is printed
again.
# print global variable value
print(global_var)

# call the function and modify the global variable


my_function()

# print the modified value of the global variable


print(global_var)

Copyright @Pritam_Chakraborty
Python Objects

• In Python all are objects, variables, functions or even values.


An object is linked with three concepts-Identify, Zero or more names, and a set of attributes.
1. Identify the Object
When the object is assigned to a variable, some memory address is allocated to the object.
The Python function to get the memory address is called id() function.

Copyright @Pritam_Chakraborty
Data Types in Python
• A data type indicates what values a variable can hold, and an operator indicates the kind of
operations performed on the values.
• Python supports numbers and floating numbers. Classification of data types as follows,

Copyright @Pritam_Chakraborty
Python Type Conversion

• Type conversion is the process of converting data of one type to


another. For example: converting int data to str.

• There are two types of type conversion in Python.

• Implicit Conversion - automatic type conversion


• Explicit Conversion - manual type conversion

Copyright @Pritam_Chakraborty
Python Implicit Type Conversion
• In certain situations, Python automatically converts one data type to another. This is
known as implicit type conversion.

Example:
integer_number = 123
float_number = 1.23

new_number = integer_number + float_number

# display new value and resulting data type


print("Value:",new_number)
print("Data Type:",type(new_number))

Copyright @Pritam_Chakraborty
Explicit Type Conversion

• In Explicit Type Conversion, users convert the data type of an object


to required data type.
• We use the built-in functions like int(), float(), str(), etc to perform
explicit type conversion.
• This type of conversion is also called typecasting because the user
casts (changes) the data type of the objects.

Example:

Copyright @Pritam_Chakraborty
num_string = '12'
num_integer = 23

print("Data type of num_string before Type Casting:",type(num_string))

# explicit type conversion


num_string = int(num_string)

print("Data type of num_string after Type Casting:",type(num_string))

num_sum = num_integer + num_string

print("Sum:",num_sum)
print("Data type of num_sum:",type(num_sum))

Copyright @Pritam_Chakraborty
Key Points For Type Conversion
• Type Conversion is the conversion of an object from one data type to
another data type.
• Implicit Type Conversion is automatically performed by the Python
interpreter.
• Python avoids the loss of data in Implicit Type Conversion.
• Explicit Type Conversion is also called Type Casting, the data types of
objects are converted using predefined functions by the user.
• In Type Casting, loss of data may occur as we enforce the object to a
specific data type.

Copyright @Pritam_Chakraborty
Operators and Expression
• Operators

Operators are contructs that are used to manipulate the value of operands.
Some basic operators includes +,-,*,and /.

Different operators supported by Python include


a) Arithmetic Operator
b) Comparison Operator
c) Assignment Operator
d) Logical Operator

Copyright @Pritam_Chakraborty
e) Unary Operators
f) Bitwise Operators
g) Membership Operators
h) Identity Operators

• Expression

An Expression in a programing language is any valid combination of


tokens that represents a value. There are two types of expressions,
a) Simple Expression, in which there is simple values
b) Complex Expression, in which one or more operators are used on
operand(s) to generate a value. Example, sum = 2 + 4, solve =
10*8/2.
Copyright @Pritam_Chakraborty
• Expression can also be classified as arithmetic expressions, logical
expressions, string expressions and relational expressions, where,

 Arithmetic Expression Consists of number and arithmetic operators


Logical Expression have literals or variables and logical operators
Relational Expression have literals or variables and relational
operators.
String expressions have string operands and string operators ( like, *
and +)

Copyright @Pritam_Chakraborty
Arithmetic Operators

Copyright @Pritam_Chakraborty
Comparison Operators

Copyright @Pritam_Chakraborty
Assignment and in-place or shortcut
operators

Copyright @Pritam_Chakraborty
Unary Operators
• Acts on Single Operands.

• Unary minus operator is different from Arithmetic


operators on two operands, Unary operands is
preceded by a unary minus sign its value is negated.

• >> a = 5
• >> b = -a
• >> print(b)
• Output: -5
Copyright @Pritam_Chakraborty
Bitwise Operators

Copyright @Pritam_Chakraborty
Truth Table For Bitwise Operator

Copyright @Pritam_Chakraborty
Verification of Bitwise Operator Output
• The bin() function is a built-in Python function that converts an
integer number into a binary string prefixed with '0b'.

• >> bin(15)  0b1111


• >> bin(7) 0b111
• >> 15 & 7  7

As 1111 & 0111  0111

Copyright @Pritam_Chakraborty
Shift Operator
• Python Support two bitwise shift operators. They are shift left (<<)
and shift right (>>). Example of Left Shift,

Copyright @Pritam_Chakraborty
• Example of Right Shift

Copyright @Pritam_Chakraborty
Logical Operators

Copyright @Pritam_Chakraborty
Membership Operator

Copyright @Pritam_Chakraborty
Identity Operator

Copyright @Pritam_Chakraborty
Operators Precedence and Associativity

Copyright @Pritam_Chakraborty
Strings
• Strings in Python are arrays of bytes representing unicode characters.
• Python does not have a character data type, a single character is
simply a string with a length of 1.
Strings in python are surrounded by either single
quotation marks, or double quotation marks.
'hello' is the same as "hello".
You can display a string literal with the print() function:
print("Hello")
print('Hello')

Copyright @Pritam_Chakraborty
• Quotes Inside Quotes
You can use quotes inside a string, as long as they don't
match the quotes surrounding the string:
• Example
print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')

• Assign String to a Variable


Assigning a string to a variable is done with the variable
name followed by an equal sign and the string:
• Example
a = "Hello"
print(a)
Copyright @Pritam_Chakraborty
• Multiline Strings
You can assign a multiline string to a variable by using three quotes:
• Example
You can use three double quotes:
• a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.""“

print(a)
Or three single quotes:
• Example
• a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.''‘

print(a)

Copyright @Pritam_Chakraborty
• Strings as an Array

Strings in Python are arrays of bytes representing unicode characters.

• Python Doesn’t have character (CHAR) data type a single character is


simply a string with a length of 1.
• Square brackets can be used to access elements of the string.

• >> a = “hello!Students”
• >> print(a[6])
• Output: S

Copyright @Pritam_Chakraborty
• Looping through strings

Since Strings in python are treated as an ARRAY, Using FOR loop we can parse
through string.

>> for x in “STUDENT":


>> print(x)

Output:
S
T
U
D
E
N
T
Copyright @Pritam_Chakraborty
• String Length

To Check the length of the string, len() function is used.

>> a = “hello”
>> print(len(a))

Output: 5

Copyright @Pritam_Chakraborty
• Check Presence of word, character, phrase etc. in a String

To check the presence of word, character, phrase etc. in a String , we can use in
keyword.

>> txt = "The best things in life are free!“


print( “life” in txt)

Output: true

Use it in IF-ELSE:-
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")

Output: Yes, 'free' is present.


Copyright @Pritam_Chakraborty
• Check if NOT

To check certain phrase or character is not present , we can use not in


keyword.

>> txt = "The best things in life are free!"


print("expensive" not in txt)

Output: True
Use it in IF-ELSE:-
txt = "The best things in life are free!"
if “expensive" not in txt:
print("Yes, ‘expensive ' is not present.")

Output: Yes, ‘expensive ' is not present.

Copyright @Pritam_Chakraborty
String Slicing
• We can return a range of characters by using the slice syntax.
• Specify the start index and the end index, separated by a colon, to
return a part of the string.
Example: Get the characters from position 2 to position 5 (not
included):
• >> b = "Hello, Student!"
>> print(b[2:5])
• Output: llo

Copyright @Pritam_Chakraborty
• Slice From the Start

By leaving out the start index, the range will start at the first character:
• Example:
#Get the characters from the start to position 5 (not included):

>> b = “Hello, Student!”


>> print(b[:5])

Output: Hello

Copyright @Pritam_Chakraborty
• Slice To the End

By leaving out the end index, the range will go to the end:
• Example
# Get the characters from position 2, and all the way to the end:
• b = "Hello, Student!"
print(b[2:])

• Output: llo, Student!

Copyright @Pritam_Chakraborty
• Negative Indexing

Use negative indexes to start the slice from the end of the
string:Example

#Get the characters:


#From: "o" in "World!" (position -5)
# To, but not included: "d" in "World!" (position -2):
>> b = “Monty Python"
print(b[-5:-2])

• Output: yth
Copyright @Pritam_Chakraborty
Modify Strings
• Upper Case

The upper() method returns the string in upper case:


a = "Hello, World!"
print(a.upper())

• Lower Case
The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())

Copyright @Pritam_Chakraborty
• Remove Whitespace

Whitespace is the space before and/or after the actual text, and
very often you want to remove this space.

Example
The strip() method removes any whitespace from the beginning
or the end:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"

Copyright @Pritam_Chakraborty
• Replace String:

The replace() method replaces a string with another


string:
a = "Hello, World!"
print(a.replace("H", "J"))

• Output: Jello, World!

Copyright @Pritam_Chakraborty
Split String

• The split() method returns a list where the text between the specified
separator becomes the list items.

• >> a = "Hello, World!"


print(a.split(",")) # returns ['Hello', ' World!']
• Output: ['Hello', ' World!']

Copyright @Pritam_Chakraborty
String Concatenation

• To concatenate, or combine, two strings you can use the + operator.

Merge variable a and b into variable c:

a = "Hello"
b = "World"
c=a+b
print(c)

• Output: HelloWorld

Copyright @Pritam_Chakraborty
Format String
• we cannot combine strings and numbers like this:

age = 36
txt = "My name is John, I am " + age
print(txt)

Output: ERROR: Traceback (most recent call last):


File "demo_string_format_error.py", line 2, in <module>
txt = "My name is John, I am " + age
TypeError: must be str, not int

Copyright @Pritam_Chakraborty
We can combine strings and numbers by using f-strings or the format() method!

F-String was introduced in Python 3.6, and is now the preferred way of formatting
strings.

To specify a string as an f-string, simply put an f in front of the string literal, and add curly
brackets {} as placeholders for variables and other operations.

>> age = 24
>> txt = f"My name is John, I am {age}"
print(txt)

Output: My name is John, I am 24


Copyright @Pritam_Chakraborty
Placeholders and Modifiers
• A placeholder can contain variables, operations, functions, and
modifiers to format the value.
>>price = 59
>>txt = f"The price is {price} dollars"
>>print(txt)
Output: The price is 59 dollars

Note: A placeholder can contain Python code, like math operations:


>> txt = f"The price is {20 * 59} rupees"
>> print(txt)
• Output: The price is 1180 rupees
Copyright @Pritam_Chakraborty
• A placeholder can include a modifier to format the value.
• A modifier is included by adding a colon : followed by a legal
formatting type, like .2f which means fixed point number with 2
decimals:

#Display the price with 2 decimals:


>>price = 59.3876
>>txt = f"The price is {price:.2f} rupees"
>>print(txt)

• Output: The price is 59.39 rupees

Copyright @Pritam_Chakraborty
Lab Practice Question:
1. Create a string made of the first, middle and last character.

Soln:
>>str1 = 'James‘
print("Original String is", str1)
# Get first character
>>res = str1[0]
# Get string size
>>l = len(str1)
# Get middle index number
>>mi = int(l / 2)
# Get middle character and add it to result
res = res + str1[mi]
# Get last character and add it to result
res = res + str1[l - 1]
print("New String:", res)

Copyright @Pritam_Chakraborty
• Exercise 2: Append new string in the middle of a given string
• s1 = "Ault" s2 = "Kelly“
• O/P: AuKellylt

Solution:
•First, get the middle index number of s1 by dividing s1’s length by 2
•Use string slicing to get the character from s1 starting from 0 to the
middle index number and store it in x
•concatenate x and s2. x = x + s2
•concatenate x and remaining character from s1
•print x

Copyright @Pritam_Chakraborty
• >>> s1 = "Ault"
• >>> s2 = "Kelly"
• >>> mi = int(len(s1) / 2)
• >>> x = s1[:mi:]
• >>> x = x + s2
• >>> x = x + s1[mi:]
• >>> print(x)

Copyright @Pritam_Chakraborty
• Exercise 3: Create a string made of the middle three characters
• str1 = "JohnDipPeta“
• O/P: Dip

• Solution:

•First, get the middle index number by dividing string length by 2.


•Use string slicing to get the middle three characters starting from the
middle index to the next two character.

Copyright @Pritam_Chakraborty
• str1 = "JohnDipPeta“
• # first get middle index number
• mi = int(len(str1) / 2)
• # use string slicing to get result characters
• res = str1[mi - 1:mi + 2]
• print("Middle three chars are:", res)

Copyright @Pritam_Chakraborty
• Exercise 4: Create a new string made of the first, middle, and last characters of
each input string

• s1 = "America"
• s2 = "Japan“
• first_char = s1[0] + s2[0]
• # get middle character from both string
• middle_char = s1[int(len(s1) / 2):int(len(s1) / 2) + 1] + s2[int(len(s2) / 2):int(len(s2)
/ 2) + 1]
• # get last character from both string
• last_char = s1[len(s1) - 1] + s2[len(s2) - 1]
• # add all
• res = first_char + middle_char + last_char
• print("Mix String is ", res)

Copyright @Pritam_Chakraborty
• Exercise 5: Arrange string characters such that lowercase letters should come first
• Str1= “PyNaTive”
• O/P = yaivePNT

• str1 = "PYnAtivE“
• print('Original String:', str1)
• lower = []
• upper = []
• for char in str1:
if char.islower():
# add lowercase characters to lower list
lower.append(char)
else:
# add uppercase characters to lower list
upper.append(char)
# Join both
list sorted_str = ''.join(lower + upper)
print('Result:', sorted_str)
Copyright @Pritam_Chakraborty
• Example 6. Count all the letters, digits, and special symbols from a given string
• Solution:
sample_str = "P@yn2at&#i5ve"
char_count = 0
digit_count = 0
symbol_count = 0
for char in sample_str:
if char.isalpha():
char_count += 1
elif char.isdigit():
digit_count += 1
# if it is not letter or digit then it is special symbol
else:
symbol_count += 1

print("Chars =", char_count, "Digits =", digit_count, "Symbol =", symbol_count)

Copyright @Pritam_Chakraborty
• Example 7: Create a mixed String using the following rules

Given two strings, s1 and s2. Write a program to create a new string s3 made
of the first char of s1, then the last char of s2, Next, the second char of s1
and second last char of s2, and so on. Any leftover chars go at the end of the
result.

• s1 = “Abc”
• s2 = “Xyz”

Copyright @Pritam_Chakraborty
• s1 = "Abc"
• s2 = "Xyz"

• # get string length


• s1_length = len(s1)
• s2_length = len(s2)

• # get length of a bigger string


• length = s1_length if s1_length > s2_length else
s2_length
• result = ""
Copyright @Pritam_Chakraborty
• # reverse s2
• s2 = s2[::-1]

• # iterate string
• # s1 ascending and s2 descending
• for i in range(length):
• if i < s1_length:
• result = result + s1[i]
• if i < s2_length:
• result = result + s2[i]

• print(result)

Copyright @Pritam_Chakraborty
• Example 8: Write a program to count occurrences of all characters within a string

• Solution:
• str1 = "Apple"

• # create a result dictionary


• char_dict = dict()

• for char in str1:


• count = str1.count(char)
• # add / update the count of a character
• char_dict[char] = count
• print('Result:', char_dict)

Copyright @Pritam_Chakraborty
• Example 9: Split a string on hyphens

Solution:

str1 = "Emma-is-a-data-scientist"
print("Original String is:", str1)

# split string
sub_strings = str1.split("-")

print("Displaying each substring")


for sub in sub_strings:
print(sub)
Copyright @Pritam_Chakraborty
• Example 10: Remove special symbols / punctuation from a string

• Solution method 1:

import string

str1 = "/*Jon is @developer & musician"


print("Original string is ", str1)

new_str = str1.translate(str.maketrans('', '', string.punctuation))

print("New string is ", new_str)

Copyright @Pritam_Chakraborty
• Solution method 2:
import re

str1 = "/*Jon is @developer & musician"


print("Original string is ", str1)

# replace special symbols with ''


res = re.sub(r'[^\w\s]', '', str1)
print("New string is ", res)

Copyright @Pritam_Chakraborty
• Example 11: Write a Python program to change a given string to a new string
where the first and last chars have been exchanged
• Before Swap : PythoN
After Swap : NythoP
Solution:
1st way:
str = "Python"
print("Before Swap :",str)
res = str[-1:] + str[1:-1] + str[:1]
print("After Swap :",res)

Copyright @Pritam_Chakraborty
2nd Way:

str = "Python"
print("Before Swap :",str)
s = str[0]
e = str[-1]
res = e + str[1:-1] + s
print("After Swap :",res)

Copyright @Pritam_Chakraborty
Escape Characters

To insert characters that are illegal in a string, use an escape


character.
An escape character is a backslash \ followed by the character you
want to insert.
An example of an illegal character is a double quote inside a string
that is surrounded by double quotes:

Copyright @Pritam_Chakraborty
• Example
• The escape character allows you to use double quotes when you
normally would not be allowed:
• >> txt = "We are the so-called \"Vikings\" from the north."

Copyright @Pritam_Chakraborty
String Methods
• Python has a set of built-in methods that you can use on strings. Note: All string methods return
new values. They do not change the original string.
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the position of where it was
found
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and returns the position of where it was
found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isascii() Returns True if all characters in the string are ascii characters
Copyright @Pritam_Chakraborty
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of where it was found
rindex() Searches the string for a specified value and returns the last position of where it was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
Copyright @Pritam_Chakraborty
zfill() Fills the string with a specified number of 0 values at the beginning

You might also like