Python Unit 1
Python Unit 1
History of python:
Python is a widely used general-purpose, high-level programming language.
It was initially designed by Guido van Rossum in 1991 and developed by Python Software
Foundation.
It was mainly developed to emphasize code readability, and its syntax allows programmers to
express concepts in fewer lines of code.
In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to [Link].
Application Of Python:
Python Applications Python is known for its general-purpose nature that makes it applicable in
almost every domain of software development. Python makes its presence in every emerging
field. It is the fastest-growing programming language and can develop any application. Some of
the globally known applications such as YouTube, BitTorrent, DropBox, etc. use Python to
achieve their functionality. Let us see some of the areas where Python excels in application
development.
Web Development
We can use Python to develop web applications. It provides libraries to handle internet protocols
such as HTML and XML, JSON, Email processing, etc. Some of the most well-known
frameworks that Python use to create these applications are Django, Flask, Pyramid, etc
Game Development
Python is also used in the development of interactive games. There are libraries such as PySoy
which is a 3D game engine supporting Python 3, PyGame which provides functionality and a
library for game development. Games such as Civilization-IV, Disney’s Toontown Online, Vega
Strike etc. have been built using Python.
Python can be used to pull a large amount of data from websites which can then be helpful in
various real-world processes such as price comparison, job listings, research and development
1
and much more. Python has libraries such as BeautifulSoup, LXML, MechanicalSoup, Python
Requests, Scrapy, etc which can be used to pull such data and be used accordingly.
This is the era of Artificial intelligence where the machine can perform the task the same as the
human. Python language is the most suitable language for Artificial intelligence or machine
learning. It consists of many scientific and mathematical libraries, which makes easy to solve
complex calculations. Some of popularly used libraries are Numpy, Pandas, Scipy, Scikit-learn,
etc.
Data is money if you know how to extract relevant information which can help you take
calculated risks and increase profits. You study the data you have, perform operations and extract
the information required. Libraries such as Pandas, NumPy help you in extracting information.
You can even visualize the data using libraries such as Matplotlib, Seaborn, which are helpful in
plotting graphs and much more.
Python is flexible to perform multiple tasks and can be used to create multimedia applications.
Video and audio applications such as TimPlayer, Cplay have been developed using Python
libraries and they provide better stability and performance compared to other media players. Few
multimedia libraries are Gstreamer, Pyglet, QT Phonon, etc.
Business Applications
Business Applications are different from normal applications covering domains such as e-
commerce, ERP and many more. They require applications which are scalable, extensible and
easily readable and Python provides us with all these features. Some real-time applications are
Odoo (formerly OpenERP), Tryton, Picalo, etc.
CAD (Computer aided design) and CAM (computer aided manufacturing) is a term that refers to
computer systems that are used to both design and manufacture products. CAD is used to
develop the 3D representation of a part of a system. Python supports a wide range of
functionalities for 3D CAD & CAM application such as FreeCAD, Fandango, CAMVOX,
HeeksCNC, AnyCAD, HeeksPython, PythonOCC, PythonCAD, Blender, Vintech RCAM, etc.
Embedded Applications
2
Python is based on C which means that it can be used to create Embedded C software for
embedded applications. This helps us to perform higher-level applications on smaller devices
which can compute Python. The most wellknown embedded application could be the Raspberry
Pi which uses Python for its computing. It can be used as a computer or like a simple embedded
board to perform high-level computations.
Python Statements In general, the interpreter reads and executes the statements line by line i.e
sequentially. Though, there are some statements that can alter this behavior like conditional
statements.
Mostly, python statements are written in such a format that one statement is only written
in a single line. The interpreter considers the ‘new line character’ as the terminator of one
instruction. But, writing multiple statements per line is also possible that you can find below.
Examples:
Output:
Welcome to Geeks for Geeks
Multiple Statements per Line We can also write multiple statements per line, but it is not a
good practice as it reduces the readability of the code. Try to avoid writing multiple statements in
a single line. But, still you can write multiple lines by terminating one statement with the help of
‘;’. ‘;’ is used as the terminator of one statement in this case.
For Example, consider the following code.
# Example
a = 10; b = 20; c = b + a
Output:
10
20
30
3
Python Indentation:
Most of the programming languages like C, C++, and Java use braces { } to define a block of
code. Python, however, uses indentation.
A code block (body of a function, loop, etc.) starts with indentation and ends with the first un
indented line. The amount of indentation is up to you, but it must be consistent throughout that
block. Generally, four whitespaces are used for indentation and are preferred over tabs.
Here is an example.
for i in range(1,11):
print(i)
if i == 5:
break
The enforcement of indentation in Python makes the code look neat and clean. This results in
Python programs that look similar and consistent. Incorrect indentation will result in
IndentationError.
Comments in Python
Comments can be used to explain Python code.
Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code.
Single Line Comment
A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and
up to the end of the line are part of the comment and the Python interpreter ignores them.
# First comment
Multi-line Comment
Python does not really have syntax for multi line comments. To add a multiline comment you
could insert a
# This is a comment.
4
# This is a comment, too.
Another way of doing this is to use triple quotes, either ''' or """. These triple quotes are generally
used for multi-line strings. But they can be used as a multi-line comment as well. Following
triple-quoted string is also ignored by Python interpreter and can be used as a multiline
comments ''' This is a multiline comment. ''
Character set
A character set is a set of valid characters acceptable by a programming language in scripting.
In this case, we are talking about the Python programming language.
the Python character set is a valid set of characters recognized by the Python language. These
are the characters we can use during writing a script in Python.
Alphabets: All capital (A-Z) and small (a-z) alphabets.
Digits: All digits 0-9.
Special Symbols: Python supports all kind of special symbols like, ” ‘ l ; : ! ~ @ # $ % ^ `
&*()_+–={}[]\.
White Spaces: White spaces like tab space, blank space, newline, and carriage return.
Other: All ASCII and UNICODE characters are supported by Python that constitutes the
Python character set.
Tokens
A token is the smallest individual unit in a python program. All statements and instructions in a
program are built with tokens. The various tokens in python are :
1. Keywords: Keywords are words that have some special meaning or significance in a
programming language. They can’t be used as variable names, function names, or any
other random purpose. They are used for their special features.
In Python we have 33 keywords some of them are: try, False, True, class, break,
continue, and, as, assert, while, for, in, raise, except, or, not, if, elif, print, import, etc.
2. Identifiers: Identifiers are the names given to any variable, function, class, list,
methods, etc. for their identification. Python is a case-sensitive language and it has
some rules and regulations to name an identifier.
5
An identifier can’t be a keyword.
For Example: Some valid identifiers are gfg, GeeksforGeeks, _geek, mega12, etc.
3. Literals or Values: Literals are the fixed values or data items used in a source code. Python
supports different types of literals such as:
(i) String Literals: The text written in single, double, or triple quotes represents the string
literals in Python. For example: “Computer Science”, ‘sam’, etc. We can also use triple quotes
to write multi-line strings.
# String Literals
a ='Hello'
b ="Geeks"
c ='''Geeks for Geeks is a
learning platform'''
# Driver code
print(a)
print(b)
print(c)
Output
Hello
Geeks
Geeks for Geeks is a
learning platform
(ii) Character Literals: Character literal is also a string literal type in which the character is
enclosed in single or double-quotes.
Python3
# Character Literals
a ='G'
b ="W"
# Driver code
print(a)
print(b)
Output:
G
W
6
(iii) Numeric Literals: These are the literals written in form of numbers. Python supports the
following numerical literals:
Integer Literal: It includes both positive and negative numbers along with 0. It doesn’t
include fractional parts. It can also include binary, decimal, octal, hexadecimal literal.
Float Literal: It includes both positive and negative real numbers. It also includes
fractional parts.
Complex Literal: It includes a+bi numeral, here a represents the real part and b represents
the complex part.
Python3
# Numeric Literals
a =5
b =10.3
c =-17
# Driver code
print(a)
print(b)
print(c)
Output
5
10.3
-17
(iv) Boolean Literals: Boolean literals have only two values in Python. These are True and
False.
Python3
# Boolean Literals
a =3
b =(a ==3)
c =True+10
# Driver code
print(a, b, c)
Output
3 True 11
(v) Special Literals: Python has a special literal ‘None’. It is used to denote nothing, no
values, or the absence of value.
Python3
# Special Literals
7
var =None
print(var)
Output
None
(vi) Literals Collections: Literals collections in python includes list, tuple, dictionary, and
sets.
1. List: It is a list of elements represented in square brackets with commas in between. These
variables can be of any data type and can be changed as well.
2. Tuple: It is also a list of comma-separated elements or values in round brackets. The values
can be of any data type but can’t be changed.
3. Dictionary: It is the unordered set of key-value pairs.
4. Set: It is the unordered collection of elements in curly braces ‘{}’.
Python3
# Literals collections
# List
my_list =[23, "geek", 1.2, 'data']
# Tuple
my_tuple =(1, 2, 3, 'hello')
# Dictionary
my_dict ={1:'one', 2:'two', 3:'three'}
# Set
my_set ={1, 2, 3, 4}
# Driver code
print(my_list)
print(my_tuple)
print(my_dict)
print(my_set)
Output
[23, 'geek', 1.2, 'data']
(1, 2, 3, 'hello')
{1: 'one', 2: 'two', 3: 'three'}
{1, 2, 3, 4}
4. Operators: These are the tokens responsible to perform an operation in an expression. The
variables on which operation is applied are called operands. Operators can be unary or binary.
Unary operators are the ones acting on a single operand like complement operator, etc. While
binary operators need two operands to operate.
8
Python3
# Operators
a =12
# Unary operator
b =~ a
# Binary operator
c =a+b
# Driver code
print(b)
print(c)
Output
-13
-1
5. Punctuators:
These are the symbols that used in Python to organize the structures, statements, and
expressions. Some of the Punctuators are: [ ] { } ( ) @ -= += *= //= **== = , etc.
OPERATORS:
In Python programming, Operators in general are used to perform operations on values and
variables. These are standard symbols used for logical and arithmetic operations. In this article,
we will look into different types of Python operators.
OPERATORS: These are the special symbols. Eg- + , * , /, etc.
OPERAND: It is the value on which the operator is applied.
Types of Operators in Python
1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Identity Operators and Membership Operators
9
Operator Description Syntax
sub=a-b
11
mul=a*b
mod=a%b
p=a**b
print(add)
print(sub)
print(mul)
print(mod)
print(p)
[/GFGTABS]
Output:
13
5
36
1
6561
Note: Refer to Differences between / and // for some interesting facts about these two Python
operators.
Comparison of Python Operators
In Python Comparison of Relational operators compares the values. It either
returns True or False according to the condition.
Operator Description Syntax
12
Operator Description Syntax
print(a>b)
print(a<b)
print(a==b)
print(a!=b)
print(a>=b)
print(a<=b)
[/GFGTABS]
Output
False
True
False
True
False
True
13
Operator Description Syntax
| Bitwise OR x|y
~ Bitwise NOT ~x
14
Operator Description Syntax
15
Operator Description Syntax
16
Operator Description Syntax
17
Example: The code uses identity operators to compare variables in Python. It checks if ‘a’ is not
the same object as ‘b’ (which is true because they have different values) and if ‘a’ is the same
object as ‘c’ (which is true because ‘c’ was assigned the value of ‘a’).
[GFGTABS] Python
a=10
b=20
c=a
print(aisnotb)
print(aisc)
[/GFGTABS]
Output
True
True
if(xnotinlist):
print("x is NOT present in given list")
else:
print("x is present in given list")
if(yinlist):
print("y is present in given list")
else:
print("y is NOT present in given list")
[/GFGTABS]
Output
x is NOT present in given list
y is present in given list
18
Ternary Operator in Python
in Python, Ternary operators also known as conditional expressions are operators that evaluate
something based on a condition being true or false. It was added to Python in version 2.5.
It simply allows testing a condition in a single line replacing the multiline if-else making the
code compact.
print(min)
[/GFGTABS]
Output:
10
ifname=="Alex"orname=="John"andage>=2:
print("Hello! Welcome.")
else:
print("Good Bye!!")
[/GFGTABS]
Output
610
Hello! Welcome.
19
Precedence and Associativity of Operators in Python
Precedence of Python Operators
The combination of values, variables, operators, and function calls is termed as an expression.
The Python interpreter can evaluate a valid expression.
For example:
>>>5 - 7
-2
But we can change this order using parentheses () as it has higher precedence than
multiplication.
The operator precedence in Python is listed in the following table. It is in descending order
(upper group has higher precedence than the lower ones).
Operators Meaning
() Parentheses
** Exponent
20
*, /, //, % Multiplication, Division, Floor division, Modulus
+, - Addition, Subtraction
^ Bitwise XOR
| Bitwise OR
or Logical OR
Python defines type conversion functions to directly convert one data type to
another which is useful in day-to-day and competitive programming. This article is
aimed at providing information about certain conversion functions.
There are two types of Type Conversion in Python:
1. Python Implicit Type Conversion
2. Python Explicit Type Conversion
Type Conversion in Python
The act of changing an object’s data type is known as type conversion. The Python
interpreter automatically performs Implicit Type Conversion. Python prevents
Implicit Type Conversion from losing data.
The user converts the data types of objects using specified functions in explicit
21
type conversion, sometimes referred to as type casting. When type casting, data
loss could happen if the object is forced to conform to a particular data type.
Implicit Type Conversion in Python
In Implicit type conversion of data types in Python, the Python interpreter
automatically converts one data type to another without any user involvement. To
get a more clear view of the topic see the below examples.
Example
As we can see the data type of ‘z’ got automatically changed to the “float” type
while one variable x is of integer type while the other variable y is of float type.
The reason for the float value not being converted into an integer instead is due to
type promotion that allows performing operations by converting data into a wider-
sized data type without any loss of information. This is a simple case of Implicit
type conversion in Python.
Python3
x =10
y =10.6
z =x +y
print(z)
Output
20.6
Explicit Type Conversion in Python
In Explicit Type Conversion in Python, the data type is manually changed by the
user as per their requirement. With explicit type conversion, there is a risk of data
loss since we are forcing an expression to be changed in some specific data type.
Various forms of explicit type conversion are explained below:
Converting integer to float
int(a, base)
This function converts any data type to an integer. ‘Base’ specifies the base in
which the string is if the data type is a string.
float(): This function is used to convert any data type to a floating-
point number.
Python3
22
# printing string converting to float
a=5
b=10
c=a+b
print( c )
e =float(c)
print(e)
Output:
15
15.0
Expressions in Python:
An expression is a combination of values, variables, operators, and calls to functions.
Expressions need to be evaluated. If you ask Python to print an expression, the
interpreter evaluates the expression and displays the result.
# Constant Expressions
x =15+1.3
print(x)
Output
16.3
2. Arithmetic Expressions: An arithmetic expression is a combination of numeric values,
operators, and sometimes parenthesis. The result of this type of expression is also a numeric
23
value. The operators used in these expressions are arithmetic operators like addition,
subtraction, etc. Here are some arithmetic operators in Python:
+ x+y Addition
– x–y Subtraction
* x*y Multiplication
/ x/y Division
// x // y Quotient
% x%y Remainder
** x ** y Exponentiation
Example:
Let’s see an exemplar code of arithmetic expressions in Python :
Python3
# Arithmetic Expressions
x =40
y =12
add =x +y
sub =x -y
pro =x *y
div =x /y
24
print(add)
print(sub)
print(pro)
print(div)
Output
52
28
480
3.3333333333333335
3. Integral Expressions: These are the kind of expressions that produce only integer results
after all computations and type conversions.
Example:
Python3
# Integral Expressions
a =13
b =12.0
c =a +int(b)
print(c)
Output
25
4. Floating Expressions: These are the kind of expressions which produce floating point
numbers as result after all computations and type conversions.
Example:
Python3
25
# Floating Expressions
a =13
b =5
c =a /b
print(c)
Output
2.6
5. Relational Expressions: In these types of expressions, arithmetic expressions are written on
both sides of relational operator (> ,< , >= , <=). Those arithmetic expressions are evaluated
first, and then compared as per relational operator and produce a boolean output in the end.
These expressions are also called Boolean expressions.
Example:
Python3
# Relational Expressions
a =21
b =13
c =40
d =37
print(p)
Output
True
26
6. Logical Expressions: These are kinds of expressions that result in either True or False. It
basically specifies one or more conditions. For example, (10 == 9) is a condition if 10 is equal
to 9. As we know it is not correct, so it will return False. Studying logical expressions, we also
come across some logical operators which can be seen in logical expressions most often. Here
are some logical operators in Python:
P and
and It returns true if both P and Q are true otherwise returns false
Q
Example:
Let’s have a look at an exemplar code :
Python3
P =(10==9)
Q =(7> 5)
# Logical Expressions
R =P andQ
S =P orQ
T =notP
print(R)
print(S)
27
print(T)
Output
False
True
True
7. Bitwise Expressions: These are the kind of expressions in which computations are
performed at bit level.
Example:
Python3
# Bitwise Expressions
a =12
x =a >> 2
y =a << 1
0010
print(x, y)
Output
3 24
8. Combinational Expressions: We can also use different types of expressions in a single
expression, and that will be termed as combinational expressions.
Example:
Python3
# Combinational Expressions
a =16
b =12
c =a +(b >> 1)
print(c)
Output
22
28
But when we combine different types of expressions or use multiple operators in
a single expression, operator precedence comes into play.
Statement:
Python Output
In Python, we can simply use the print() function to print output. For example,
print('Python is powerful')
Here, the print() function displays the string enclosed inside the single quotation.
Syntax of print()
In the above code, the print() function is taking a single parameter.
However, the actual syntax of the print function accepts 5 parameters
Here,
29
object - value(s) to be printed
sep (optional) - allows us to separate multiple objects inside print().
end (optional) - allows us to add add specific values like new line "\n", tab "\t"
file (optional) - where the values are printed. It's default value is [Link] (screen)
flush (optional) - boolean specifying if the output is flushed or buffered. Default: False
print('Good Morning!')
print('It is rainy today')
Run Code
Output
Good Morning!
It is rainy today
In the above example, the print() statement only includes the object to be printed. Here, the
value for end is not used. Hence, it takes the default value '\n'.
So we get the output in two different lines.
30
Run Code
Output
Notice that we have included the end= ' ' after the end of the first print() statement.
Hence, we get the output in a single line separated by space.
Output
In the above example, the print() statement includes multiple items separated by a comma.
Notice that we have used the optional parameter sep= ". " inside the print() statement.
Hence, the output includes items separated by . not comma.
We can also use the print() function to print Python variables. For example,
number = -10.6
31
name = "Programiz"
# print literals
print(5)
# print variables
print(number)
print(name)
Run Code
Output
5
-10.6
Programiz
Output formatting
Sometimes we would like to format our output to make it look attractive. This can be done by
using the [Link]() method. For example,
x=5
y = 10
Here, the curly braces {} are used as placeholders. We can specify the order in which they are
printed by using numbers (tuple index).
To learn more about formatting the output, visit Python String format().
32
Python Input
While programming, we might want to take the input from the user. In Python, we can use
the input() function.
Syntax of input()
input(prompt)
Output
Enter a number: 10
You Entered: 10
Data type of num: <class 'str'>
In the above example, we have used the input() function to take input from the user and stored
the user input in the num variable.
It is important to note that the entered value 10 is a string, not a number.
So, type(num) returns <class 'str'>.
To convert user input into a number we can use int() or float() functions as:
Here, the data type of the user input is converted from string to integer .
33
Data Types in Python:
A data type in Python is a classification of specific types of data by a certain value or certain
types of mathematical or logical operations.
The way that data items are categorized or classified is known as their data type. It stands for the
type of value that indicates the types of operations that can be carried out on a specific set of
data. In this programming,
Types of Data Types in Python
Python has various built-in data types which will be discussed in this article:
In Python, data with a numeric value is represented by the numeric data type.
Python programming language supports four different numerical types −
1. int (signed integers) (eg 10)
2. long (long integers, they can also be represented by octal and hexadecimal)
(eg0122L)
3. float (floating point real values) (eg15.20)
4. complex (complex numbers) (eg3.14j)
# integer variable.
a=150
print("The type of variable having value", a, " is ", type(a))
# float variable.
b=20.846
print("The type of variable having value", b, " is ", type(b))
# complex variable.
c=18+3j
print("The type of variable having value", c, " is ", type(c))
Run Code >>
34
In this code, three variables (a, b, and c) are defined with three different data types (integer, float,
and complex), and each variable's type and value are printed.
Output
A group of one or more characters enclosed in a single, double, or triple quote is called
a string in python.
A character in Python is just a string with a length of one; there is no character data type.
The str class is used to represent it.
With the help of this code, you can see how to do many string operations in Python, such as
printing the complete string, accessing particular characters, slicing the string to get a substring,
repeating the text, and concatenating it with another string.
Output
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Python list is an arranged grouping of the same or dissimilar elements that are enclosed
by brackets [] and separated by commas.
Use the index number to retrieve the list entries.
35
To access a particular item in a list, use the index operator [].
Working with Python lists is shown by this code in the Python Editor. It introduces two lists,
"list" and "tiny list," and it illustrates several list actions, such as printing the complete list,
accessing specific components, slicing to extract a sublist, repeating a list, and concatenating two
lists.
Output
36
print (tuple + tinytuple) # Prints concatenated tuples
Run Code >>
Python tuples are used in this code to show how they work. It introduces two tuples, "tuple" and
"tinytuple," defines them, and illustrates a number of tuple operations, such as publishing the
complete tuple, accessing each member, slicing to extract a sub-tuple, repeating a tuple, and
concatenating two tuples.
Output
Range() in Python is a built-in function that returns a series of numbers that begin at 0
and increase by 1 until they reach a predetermined number.
Utilizing a for and while loop in python, we use the range() method to produce a series of
numbers.
This program iterates over numbers from 1 to 4 (inclusive) and writes each one on a separate line
using a for loop in python.
Output
1
2
3
4
Python's dictionary is an unordered collection of data values that is used to store data
values in a map-like fashion.
Unlike other data types, which only include a single value per element, dictionaries
contain a key-value pair.
37
The dictionary contains key-value pairs to make it more effective.
In a dictionary, a colon (:) separates each key-value pair, while a comma separates each
key.
A dictionary in Python can be made by enclosing a list of elements in curly {} braces and
separating them with commas.
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'Scholar-Hat','code':6734, 'dept': 'sales'}
print (dict['one']) # Prints value for 'one' key
print (dict[2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print ([Link]()) # Prints all the keys
print ([Link]()) # Prints all the values
Run Code >>
The use of dictionaries in Python is shown by the following code. It performs several activities,
such as accessing values by keys, printing the complete dictionary, and showing keys and values
individually for 'tinydict', and defines three dictionaries: 'dict', and 'tinydict'.
Output
This is one
This is two
{'name': 'Scholar-Hat', 'code': 6734, 'dept': 'sales'}
dict_keys(['name', 'code', 'dept'])
dict_values(['Scholar-Hat', 6734, 'sales'])
One of the built-in data types in Python is the boolean type, which can represent either
True or False.
Any expression can be evaluated for value using the Python bool() method, which returns
True or False depending on the expression.
a = True
# display the value of a
print(a)
38
Run Code >>
The variable 'a' is given the Boolean value "True" by the following code, which then prints both
the value ("True") and the data type ("bool") of the variable.
Output
true
<class'bool'>
A set is an unsorted collection of distinct components. This means that set elements
cannot be repeated, and the order in which they are kept is irrelevant.
Sets are changeable, which means that after they are constructed, their elements can be
added or withdrawn. A set's elements, on the other hand, cannot be modified in place.
Curly brackets {}are used to define sets.
my_set = {1, 2, 3, 4, 5}
print(my_set)
Run Code >>
This code generates the set my_set and assigns the numbers 1, 2, 3, 4, and 5 to it. The contents of
the set are then printed to the console. Output
{1, 2, 3, 4, 5}
What is the data type conversion function?
In Python, the process of converting an object's data type from one type to another is
referred to as data type conversion.
In Python, there are two primary methods for converting data types:
1. Implicit Type Conversion
2. Explicit Type Conversion
39
In this code, the numbers 1 and 2.2 are converted to string representations and assigned to
variables 'a' and 'b', respectively. The string "3.3" is already present in variable "c". Following
that, it prints the values of "a," "b," and "c," producing the output.
Python Strings
Here, we have created a string variable named string1. The variable is initialized with the
string "Python Programming".
name = "Python"
print(name)
Output
40
Python
I love Python.
In the above example, we have created string-type variables: name and message with
values "Python" and "I love Python" respectively.
Here, we have used double quotes to represent strings, but we can use single quotes too.
Indexing: One way is to treat strings as a list and use index values. For example,
greet = 'hello'
Negative Indexing: Similar to a list, Python allows negative indexing for its strings. For
example,
greet = 'hello'
Slicing: Access a range of characters in a string by using the slicing operator colon :. For
example,
greet = 'Hello'
41
Run Code
Note: If we try to access an index out of the range or use numbers other than an integer, we will
get errors.
Output
However, we can assign the variable name to a new string. For example,
42
# multiline string
message = """
Never gonna give you up
Never gonna let you down
"""
print(message)
Run Code
Output
In the above example, anything inside the enclosing triple quotes is one multiline
string.
43
Run Code
Output
False
True
1. str1 and str2 are not equal. Hence, the result is False .
# using + operator
result = greet + name
print(result)
In the above example, we have used the + operator to join two strings: greet and name .
44
Iterate Through a Python String
We can iterate through a string using a for loop. For example,
greet = 'Hello'
Output
H
e
l
l
o
# Output: 5
Run Code
45
String Membership Test
We can test if a substring exists within a string or not, using the keyword in .
print('a'in'program') # True
print('at'notin'battle') # False
Run Code
String methods:
The upper() method converts all lowercase characters in a string into uppercase
characters and returns it.
Example
print(capitalized_string)
46
[Link] String count()
The lower() method converts all uppercase characters in a string into lowercase
characters and returns it.
Example
message = 'PYTHON IS FUN'
The split() method breaks down a string into a list of substrings using a chosen
separator.
Example
47
[Link] String find()
The find() method returns the index of first occurrence of the substring (if found). If
not found, it returns -1.
Example
message = 'Python is a fun programming language'
# Output: 12
The index() method returns the index of a substring inside the string (if found). If the
substring is not found, it raises an exception.
Example
text = 'Python is fun'
print(result)
# Output: 7
A Python String object is immutable, so you can’t change its value. Any method that
manipulates a string value returns a new String object.
The examples in this tutorial use the Python interactive console in the command line to
demonstrate different methods that remove characters.
Remove Characters From a String Using the replace() Method
The String replace() method replaces a character with a new character. You can remove a
character from a string by providing the character(s) to replace as the first argument and an
empty string as the second argument.
48
Declare the string variable:
1. s = 'abc12321cba'
2.
Copy
Output
bc12321cb
The output shows that both occurrences of the character a were removed from the string.
Remove a Substring from a String Using the replace() Method
The replace() method takes strings as arguments, so you can also replace a
word in string.
Declare the string variable:
1. s = 'Helloabc'
2.
Copy
1. print([Link]('Hello', ''))
2.
Copy
Output
abc
The output shows that the string Hello was removed from the input string.
Remove Characters From a String Using the translate() Method
The Python string translate() method replaces each character in the string using the given
mapping table or dictionary.
1. s = 'abc12321cba'
2.
Copy
49
Get the Unicode code point value of a character and replace it with None:
1. print([Link]({ord('b'): None}))
2.
Copy
Output
ac12321ca
The output shows that both occurrences of the b character were removed from the string as
defined in the custom dictionary.
[Link]()
islower() parameters
The islower() method doesn't take any parameters.
50
Example 1: Return Value from islower()
s = 'this is good'
print([Link]())
Output
True
True
False
[Link]()
51
Return value from String isupper()
The isupper() method returns:
True if all characters in a string are uppercase characters
False if any characters in a string are lowercase characters
# lowercase string
string = "THIS IS not GOOD!"
print([Link]());
Run Code
Output
True
True
False
52
print(f'{name} is from {country}')
Run Code
Output
Cathy is from UK
53