Module -2
String Handling
contents
• Assigning Values to Variables
• Multiple Assignment
• Standard Data Types
• Python Strings
• Data Type Conversion
Assigning Values to Variables
Variables are containers for storing data values. Python has no
command for declaring a variable.
A variable is created the moment you first assign a value to it.
For example:-
Program=“python”
Num=5
Print(program)
Print(num)
How to decleare variables name
• Variable Names
• A variable can have a short name (like x and y) or a more descriptive
name (age, carname, total_volume). Rules for Python variables:A
variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different
variables)
• A variable name cannot be any of the python keywoards.
1. Multiple Assignment
x, y, z = "Orange", "Banana", "Cherry“
print(x)
print(y)
print(z)
Standard Data Types
• In programming, data type is an important concept.
• Variables can store data of different types, and different types can do different things.
• Python has the following data types built-in by default, in these categories:
Text type : str
Numeric Types: int,flat,complex
sequence types: list, tuple, range
Mapping type: dictionary
Set type: Set , frozen set
Boolean type: bool
Python Strings
• Strings in python are surrounded by either single quotation marks, or
double quotation marks.
• ‘python' is the same as “python".
Slicing
• You 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.
Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])
Python - Modify Strings
Upper case:-
a = "Hello, World!"
print(a.upper())
Ther upper() method returns the string in upper case().
lower case:-
a = "Hello, World!"
print(a.lower())
Ther lower() method returns the string in upper case().
String Concatenation
• To concatenate, or combine, two strings you can use the + operator.
a = "Hello"
b = "World"
c=a+b
print(c)
Data Type Conversion
• Let's see an example where Python promotes the conversion of the
lower data type (integer) to the higher data type (float) to avoid data
loss.
Int_num=123
Float_num=1.23
new_number=int_num+float_num
Print(“value”,new_number)
Print(“d type”,type(new_number))
example
a = 15
print("Data type of a:",type(a))
b = 7.6
print("Data type of b:",type(b))
c=a+b
print("The value of c:", c)
print("Data type of c:",type(c))
d = "Priya"
print("Data type of d:",type(d))