You are on page 1of 321

Python Syntax

Last update on February 28 2020 12:16:01 (UTC/GMT +8 hours)

Introduction
A Python program is read by a parser. Python was designed to be a highly
readable language. The syntax of the Python programming language is the set of
rules which defines how a Python program will be written.

Python Line Structure:

A Python program is divided into a number of logical lines and every logical line
is terminated by the token NEWLINE. A logical line is created from one or more
physical lines.
A line contains only spaces, tabs, formfeeds possibly a comment, is known as a
blank line, and Python interpreter ignores it.
A physical line is a sequence of characters terminated by an end-of-line
sequence (in windows it is called CR LF or return followed by a linefeed and in
Unix, it is called LF or linefeed). See the following example.

Comments in Python:

A comment begins with a hash character(#) which is not a part of the string literal
and ends at the end of the physical line. All characters after the # character up to
the end of the line are part of the comment and the Python interpreter ignores
them. See the following example. It should be noted that Python has no multi-
lines or block comments facility.

Joining two lines:

When you want to write a long code in a single line you can break the logical line
in two or more physical lines using backslash character(\). Therefore when a
physical line ends with a backslash characters(\) and not a part of a string literal
or comment then it can join another physical line. See the following example.

Multiple Statements on a Single Line:


You can write two separate statements into a single line using a semicolon (;)
character between two line.

Indentation:

Python uses whitespace (spaces and tabs) to define program blocks whereas
other languages like C, C++ use braces ({}) to indicate blocks of codes for class,
functions or flow control. The number of whitespaces (spaces and tabs) in the
indentation is not fixed, but all statements within the block must be the indented
same amount. In the following program, the block statements have no
indentation.
 

This is a program with single space indentation.

This is a program with single tab indentation.


 

Here is an another program with an indentation of a single space + a single tab.

Python Coding Style:

 Use 4 spaces per indentation and no tabs.


 Do not mix tabs and spaces. Tabs create confusion and it is recommended to use
only spaces.

 Maximum line length : 79 characters which help users with a small display.

 Use blank lines to separate top-level function and class definitions and single blank line to
separate methods definitions inside a class and larger blocks of code inside functions.

 When possible, put inline comments (should be complete sentences).

 Use spaces around expressions and statements.

Python Reserve words:

The following identifiers are used as reserved words of the language, and cannot
be used as ordinary identifiers.

False class finally is

None continue for lambda

True def from nonlocal

and del global not

as el if or

assert else import pass

break except in raise

Python print() function


Last update on February 28 2020 12:14:53 (UTC/GMT +8 hours)

print() function
The print statement has been replaced with a print() function, with keyword
arguments to replace most of the special syntax of the old print statement.

The print statement can be used in the following ways :

 print("Good Morning")

 print("Good", <Variable Containing the String>)

 print("Good" + <Variable Containing the String>)

 print("Good %s" % <variable containing the string>)

In Python, single, double and triple quotes are used to denote a string. Most use
single quotes when declaring a single character. Double quotes when declaring a
line and triple quotes when declaring a paragraph/multiple lines.

Commands
print(<el_1>, ..., sep=' ', end='\n', file=sys.stdout,
flush=False)

 Use 'file=sys.stderr' for errors.

 Use 'flush=True' to forcibly flush the stream.

Pretty Print
from pprint import pprint
pprint(<collection>, width=80, depth=None)

 Levels deeper than 'depth' get replaced by '...'.

Double Quotes Use:

Example:
print("Python is very simple language")

Copy
Output:
Python is very simple language
Single Quotes Use:
Example:
print('Hello')

Copy
Output:
Hello
Triple Quotes Use:

Example:
print("""Python is very popular language.

It is also friendly language.""")

Copy
Output:
Python is very Popular Language.
It is also friendly language.
Variable Use:

Strings can be assigned to variable say string1 and string2 which can called
when using the print statement.

Example:
str1 = 'Wel'

print(str1,'come')

Copy
Output:
Wel come
Example:
str1 = 'Welcome'

str2 = 'Python'

print(str1, str2)

Copy
Output:
Welcome Python
String Concatenation:

String concatenation is the "addition" of two strings. Observe that while


concatenating there will be no space between the strings.

Example:
str1 = 'Python'

str2 = ':'

print('Welcome' + str1 + str2)

Copy
Output:
WelcomePython:
Using as String:

%s is used to refer to a variable which contains a string.

Example:
str1 = 'Python'

print("Welcome %s" % str1)

Copy
Output:
Welcome Python
Using other data types:

Similarly, when using other data types

 %d -> Integer

 %e -> exponential

 %f -> Float

 %o -> Octal

 %x -> Hexadecimal
This can be used for conversions inside the print statement itself.

Using as Integer:

Example:
print("Actual Number = %d" %15)

Copy
Output:
Actual Number = 15
Using as Exponential:

Example:
print("Exponential equivalent of the number = %e" %15)

Copy
Output:
Exponential equivalent of the number = 1.500000e+01
Using as Float:

Example:
print("Float of the number = %f" %15)

Copy
Output:
Float of the number = 15.000000
Using as Octal:

Example:
print("Octal equivalent of the number = %o" %15)

Copy
Output:
Octal equivalent of the number = 17
Using as Hexadecimal:

Example:
print("Hexadecimal equivalent of the number = %x" %15)

Copy
Output:
Hexadecimal equivalent of the number = f
Using multiple variables:

When referring to multiple variables parenthesis is used.

Example:
str1 = 'World'

str2 = ':'

print("Python %s %s" %(str1,str2))

Copy
Output:
Python World :
Other Examples of Print Statement:

The following are other different ways the print statement can be put to use.

Example-1:

% is used for %d type word


print("Welcome to %%Python %s" %'language')

Copy
Output:
Welcome to %Python language
Example-2:

\n is used for Line Break.


print("Sunday\nMonday\nTuesday\nWednesday\nThursday\nFriday\nSaturday")

Copy
Output:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Example-3:

Any word print multiple times.


print('-w3r'*5)

Copy
Output:
-w3r-w3r-w3r-w3r-w3r
Example-4:

\t is used for tab.


print("""

Language:

\t1 Python

\t2 Java\n\t3 JavaScript

""")

Copy
Output:
Language:
1 Python
2 Java
3 JavaScript
Precision Width and Field Width:

Field width is the width of the entire number and precision is the width towards
the right. One can alter these widths based on the requirements.

The default Precision Width is set to 6.

Example-1:
Notice upto 6 decimal points are returned. To specify the number of decimal
points, '%(fieldwidth).(precisionwidth)f' is used.
print("%f" % 5.1234567890)

Copy
Output:
5.123457
Example-2:

Notice upto 5 decimal points are returned


print("%.5f" % 5.1234567890)

Copy
Output:
5.12346
Example-3:

If the field width is set more than the necessary than the data right aligns itself to
adjust to the specified values.
print("%9.5f" % 5.1234567890)

Copy
Output:
5.12346
Example-4:

Zero padding is done by adding a 0 at the start of fieldwidth.


print("%015.5f" % 5.1234567890)

Copy
Output:
000000005.12346
Example-5:

For proper alignment, a space can be left blank in the field width so that when a
negative number is used, proper alignment is maintained.
print("% 9f" % 5.1234567890)

print("% 9f" % -5.1234567890)

Copy
Output:
5.123457
-5.123457
Example-6:

'+' sign can be returned at the beginning of a positive number by adding a + sign
at the beginning of the field width.
print("%+9f" % 5.1234567890)

print("% 9f" % -5.1234567890)

Copy
Output:
+5.123457
-5.123457
Example-7:

As mentioned above, the data right aligns itself when the field width mentioned is
larger than the actually field width. But left alignment can be done by specifying a
negative symbol in the field width.
print("%-9.4f" % 5.1234567890)

Copy
Output:
5.1235

Python Variable
Last update on February 28 2020 12:09:27 (UTC/GMT +8 hours)

Variable and Value


 A variable is a memory location where a programmer can store a value. Example : roll_no,
amount, name etc.

 Value is either string, numeric etc. Example : "Sara", 120, 25.36

 Variables are created when first assigned.

 Variables must be assigned before being referenced.

 The value stored in a variable can be accessed or updated later.

 No declaration required

 The type (string, int, float etc.) of the variable is determined by Python

 The interpreter allocates memory on the basis of the data type of a variable.

Python Variable Name Rules

 Must begin with a letter (a - z, A - B) or underscore (_)

 Other characters can be letters, numbers or _

 Case Sensitive

 Can be any (reasonable) length


 There are some reserved words which you cannot use as a variable name because Python
uses them for other things.

Good Variable Name

 Choose meaningful name instead of short name. roll_no is better than rn.

 Maintain the length of a variable name. Roll_no_of_a-student is too long?

 Be consistent; roll_no or RollNo

 Begin a variable name with an underscore(_) character for a special case.

Python Assignment Statements


The assignment statement creates new variables and gives them values. Basic
assignment statement in Python is :

Syntax:
<variable> = <expr>
Where the equal sign (=) is used to assign value (right side) to a variable name
(left side). See the following statements :
>>> Item_name = "Computer" #A String

>>> Item_qty = 10 #An Integer

>>> Item_value = 1000.23 #A floating point

>>> print(Item_name)

Computer

>>> print(Item_qty)

10

>>> print(Item_value)

1000.23

>>>
Copy
One thing is important, assignment statement read right to left only.

Example:

a = 12 is correct, but 12 = a does not make sense to Python, which creates a


syntax error. Check it in Python Shell.
>>> a = 12

>>> 12 = a

SyntaxError: can't assign to literal

>>>

Copy

Multiple Assignment
The basic assignment statement works for a single variable and a single
expression. You can also assign a single value to more than one variables
simultaneously.

Syntax:
var1=var2=var3...varn= = <expr>
Example:
x = y = z = 1
Now check the individual value in Python Shell.
>>> x = y = z = 1

>>> print(x)

>>> print(y)

>>> print(z)

1
>>>

Copy
Here is an another assignment statement where the variables assign many
values at the same time.

Syntax:
<var>, <var>, ..., <var> = <expr>, <expr>, ..., <expr>
Example:
x, y, z = 1, 2, "abcd"
In the above example x, y and z simultaneously get the new values 1, 2 and
"abcd".
>>> x,y,z = 1,2,"abcd"

>>> print(x)

>>> print(y)

>>> print(z)

abcd

Copy
You can reuse variable names by simply assigning a new value to them :
>>> x = 100

>>> print(x)

100

>>> x = "Python"

>>> print(x)

Python

>>>

Copy
Other ways to define value
>>> five_millions = 5_000_000

>>> five_millions

Copy
Output:
5000000
>>> small_int = .35

>>> small_int

Copy
Output:
0.35
>>> c_thousand = 10e3

>>> c_thousand

Copy
Output:
10000.0

Swap variables
Python swap values in a single line and this applies to all objects in python.

Syntax:
var1, var2 = var2, var1
Example:
>>> x = 10

>>> y = 20

>>> print(x)

10
>>> print(y)

20

>>> x, y = y, x

>>> print(x)

20

>>> print(y)

10

>>>

Copy

Local and global variables in Python


In Python, variables that are only referenced inside a function are implicitly
global. If a variable is assigned a value anywhere within the function’s body, it’s
assumed to be a local unless explicitly declared as global.

Example:

var1 = "Python"

def func1():

var1 = "PHP"

print("In side func1() var1 = ",var1)

def func2():

print("In side func2() var1 = ",var1)

func1()

func2()

Copy
Output:
In side func1() var1 = PHP
In side func2() var1 = Python
You can use a global variable in other functions by declaring it as global keyword
:

Example:

def func1():

global var1

var1 = "PHP"

print("In side func1() var1 = ",var1)

def func2():

print("In side func2() var1 = ",var1)

func1()

func2()

Copy
Output:
In side func1() var1 = PHP
In side func2() var1 = PHP

Python Data Type


Last update on February 28 2020 12:11:51 (UTC/GMT +8 hours)

Introduction
Type represents the kind of value and determines how the value can be used. All
data values in Python are encapsulated in relevant object classes. Everything in
Python is an object and every object has an identity, a type, and a value. Like
another object-oriented language such as Java or C++, there are several data
types which are built into Python. Extension modules which are written in C,
Java, or other languages can define additional types.

To determine a variable's type in Python you can use the type() function. The
value of some objects can be changed. Objects whose value can be changed are
called mutable and objects whose value is unchangeable (once they are created)
are called immutable. Here are the details of Python data types

Numbers
Numbers are created by numeric literals. Numeric objects are immutable, which
means when an object is created its value cannot be changed.

Python has three distinct numeric types: integers, floating point numbers, and
complex numbers. Integers represent negative and positive integers without
fractional parts whereas floating point numbers represents negative and positive
numbers with fractional parts. In addition, Booleans are a subtype of plain
integers. See the following statements in Python shell.
Floats and Integers
>>> x = 8

>>> y = 7

>>> x+y

>>> x-y

>>> x/y

>>> x*y

Copy

Output:
15
1
1.1428571428571428
56
Exponent
>>> 4**3

>>> 3**4

Copy

Output:
64
81
inter division
>>> 12/3

>>> 64//4

>>> 15//3

Copy

Output:
4.0
16
5
Remainder
>>> 15 % 4

Copy

Output:
3
Mathematically, a complex number (generally used in engineering) is a number
of the form A+Bi where i is the imaginary number. Complex numbers have a real
and imaginary part. Python supports complex numbers either by specifying the
number in (real + imagJ) or (real + imagj) form or using a built-in method
complex(x, y). See the following statements in Python Shell.
Self-assignment
>>> count = 0

>>> count +=2

>>> count

Copy

Output:
2
>>> count -=2

>>> count

Copy

Output:
0
>>> count +=2

>>> count *=4


>>> count

Copy

Output:
8
>>> count **=4

>>> count

Copy

Output:
4096
>>> count /=4

>>> count

Copy

Output:
1024.0
>>> count//=4

>>> count

Copy

Output:
256.0
>>> 15.0 //2

Copy

Output:
7.0
Order of operations
>>> (3+12) / 3

>>> 15 / (3 + 2)

Copy
Output:
5.0
3.0

Boolean (bool)
The simplest build-in type in Python is the bool type, it represents the truth values
False and True. See the following statements in Python shell.

Strings
In Python, a string type object is a sequence (left-to- right order) of characters.
Strings start and end with single or double quotes Python strings are immutable.
Single and double quoted strings are same and you can use a single quote within
a string when it is surrounded by double quote and vice versa. Declaring a string
is simple, see the following statements.
Special characters in strings
The backslash (\) character is used to introduce a special character. See the
following table.

Escape sequence Meaning

\n Newline

\t Horizontal Tab

\\ Backslash
\' Single Quote

\" Double Quote

See the following statements on special characters.

String indices and accessing string elements


Strings are arrays of characters and elements of an array can be accessed using
indexing. Indices start with 0 from left side and -1 when starting from right side.

string1 ="PYTHON TUTORIAL"

Character P Y T H O N   T U T

Index (from left)  0 1 2  3 4 5 6  7 8 9


Index (from right) -15 -14 -13 -12 -11 -10 -9 -8 -7 -

See the following statements to access single character from various positions.

Strings are immutable


Strings are immutable character sets. Once a string is generated, you can not
change any character within the string. See the following statements.
'in' operator in Strings
The 'in' operator is used to check whether a character or a substring is present in
a string or not. The expression returns a Boolean value. See the following
statements.
String Slicing
To cut a substring from a string is called string slicing. Here two indices are used
separated by a colon (:). A slice 3:7 means indices characters of 3rd, 4th, 5th
and 6th positions. The second integer index i.e. 7 is not included. You can use
negative indices for slicing. See the following statements.

Conversion
>>> float("4.5")

>>> int("25")
>>> int(5.625)

>>> float(6)

>>> int(True)

>>> float(False)

>>> str(True)

>>> bool(0)

>>> bool('Hello world')

>>> bool(223.5)

Copy

Output:
4.5
25
5
6.0
1
0.0
'True'
False
True
True

Tuples
A tuple is a container which holds a series of comma-separated values (items or
elements) between parentheses. Tuples are immutable (i.e. you cannot change
its content once created) and can hold mix data types.

Creating Tuples
 

To create an empty tuple or create a tuple with single element use the following
commands.

Elements of a tuple are indexed like other sequences. The tuple indices start at
0. See the following statements.
 

Tuples are immutable which means it's items values are unchangeable. See the
following statements.

 
Slicing a tuple
Like other sequences like strings, tuples can be sliced. Slicing a tuple creates a
new tuple but it does not change the original tuple.

Using + and * operators in Tuples


Use + operator to create a new tuple that is a concatenation of tuples and use *
operator to repeat a tuple. See the following statements.
 

Lists
A list is a container which holds comma-separated values (items or elements)
between square brackets where Items or elements need not all have the same
type.

Creating Lists
 

A list without any element is called an empty list. See the following statements.

List indices
List indices work the same way as string indices, list indices start at 0. If an index
has a positive value it counts from the beginning and similarly it counts backward
if the index has a negative value. As positive integers are used to index from the
left end and negative integers are used to index from the right end, so every item
of a list gives two alternatives indices. Let create a list called color_list with four
items.
color_list=["RED", "Blue", "Green", "Black"]

Item RED Blue Gree

Index (from left)  0  1  2

Index (from right) -4 -3 -2

If you give any index value which is out of range then interpreter creates an error
message. See the following statements.

 
List Slices
Lists can be sliced like strings and other sequences. The syntax of list slices is
easy :
sliced_list = List_Name[startIndex:endIndex]
This refers to the items of a list starting at index startIndex and stopping just
before index endIndex. The default values for list are 0 (startIndex) and the end
(endIndex) of the list. If you omit both indices, the slice makes a copy of the
original list. See the following statements.

Lists are Mutable


Items in the list are mutable i.e. after creating a list you can change any item in
the list. See the following statements.
 

Using + and * operators in List


Use + operator to create a new list that is a concatenation of two lists and use *
operator to repeat a list. See the following statements.

 
Sets
A set is an unordered collection of unique elements. Basic uses include dealing
with set theory (which support mathematical operations like union, intersection,
difference, and symmetric difference) or eliminating duplicate entries. See the
following statements.

Dictionaries
Python dictionary is a container of the unordered set of objects like lists.The
objects are surrounded by curly braces { }. The items in a dictionary are a
comma-separated list of key:value pairs where keys and values are Python data
type. Each object or value accessed by key and keys are unique in the
dictionary. As keys are used for indexing, they must be the immutable type
(string, number, or tuple). You can create an empty dictionary using empty curly
braces

None
This type has a single value. There is a single object with this value. This object
is accessed through the built-in name None. It is used to signify the absence of a
value in many situations, e.g., it is returned from functions that don't explicitly
return anything. Its truth value is false.

Python Operators
Last update on June 06 2020 10:33:31 (UTC/GMT +8 hours)

Operators and Operands


In computer programming languages operators are special symbols which
represent computations, conditional matching etc. The values the operator uses
are called operands.
c = a + b
Here a and b are called operands and '+' is an operator
Python supports following operators.

Contents:

 Operators commands

 Arithmetic Operators

 Comparison Operators

 Logical Operators

 Assignment Operators

 Bitwise Operator

 Conditional Operators

 Operator precedence

Operator: Commands

Module of functions that provide the functionality of operators.


from operator import add, sub, mul, truediv, floordiv, mod, pow,
neg, abs
from operator import eq, ne, lt, le, gt, ge
from operator import and_, or_, not_
from operator import itemgetter, attrgetter, methodcaller
import operator as op
sorted_by_second = sorted(<collection>, key=op.itemgetter(1))
sorted_by_both = sorted(<collection>, key=op.itemgetter(1, 0))
product_of_elems = functools.reduce(op.mul, <collection>)
LogicOp = enum.Enum('LogicOp', {'AND': op.and_, 'OR' :
op.or_})
last_el = op.methodcaller('pop')(<list>)

Python Arithmetic Operators

Operator Name Example Result


+ Addition x+y Sum of x and y.

- Subtraction x-y Difference of x and y.

* Multiplication x*y Product of x and y.

/ Division x/y Quotient of x and y.

% Modulus x%y Remainder of x divided by y.

** Exponent x**y x**y will give x to the power y

// Floor Division x/ y The division of operands where the result is the quotient in which th

See the following statements in Python Shell.

 
Python Comparison Operators

Operator Name Example Result

== Equal x==y True if x is exactly equal to y.

!= Not equal x!=y True if x is exactly not equal to y.

> Greater than x>y True if x (left-hand argument) is greater than y (r

< Less than x<y True if x (left-hand argument) is less than y (righ

>= Greater than or equal to x>=y True if x (left-hand argument) is greater than or e

<= Less than or equal to x<=y True if x (left-hand argument) is less than or equa

See the following statements in Python Shell.


 

Python Logical Operators

Operator Example Result

and (x and y) is True if both x and y are true.

or (x or y) is True if either x or y is true.

not (x not y) If a condition is true then Logical not operator will make false.

See the following statements in Python Shell.


 

Python Assignment Operators

Operator Shorthand Expression Description

+= x+=y x = x + y Adds 2 numbers and assigns the result to left operand.

-= x-= y x = x -y Subtracts 2 numbers and assigns the result to left operand.

*= x*= y x = x*y Multiplies 2 numbers and assigns the result to left operand.

/= x/= y x = x/y Divides 2 numbers and assigns the result to left operand.

%= x%= y x = x%y Computes the modulus of 2 numbers and assigns the result to left

**= x**=y x = x**y Performs exponential (power) calculation on operators and assign
//= x//=y x = x//y Performs floor division on operators and assign value to the left o

See the following statements in Python Shell.

Python Bitwise Operators

Operator Shorthand Expression Description


& And x&y Bits that are set in both x and y are se

| Or x|y Bits that are set in either x or y are set

^ Xor x^y Bits that are set in x or y but not both

~ Not ~x Bits that are set in x are not set, and v

<< Shift left x <<y Shift the bits of x, y steps to the left

>> Shift right x >>y Shift the bits of x, y steps to the right.

# Each step means 'multiply by two'


* Each step means 'divide by two'

Conditional Operators
Conditional expressions or ternary operator have the lowest priority of all Python
operations. The expression x if C else y first evaluates the condition, C (not x); if
C is true, x is evaluated and its value is returned; otherwise, y is evaluated and
its value is returned.

Operator precedence
Operator precedence determines how operators are parsed concerning each
other. The following table summarizes the operator precedence in Python, from
lowest precedence (least binding) to highest precedence (most binding).
Operators in the same box have the same precedence. Unless the syntax is
explicitly given, operators are binary. Operators in the same box group left to
right (except for exponentiation, which groups from right to left).
Note: Comparisons, membership tests, and identity tests, all have the same
precedence and have a left-to-right chaining feature as described in the
Comparisons section.

Operator Name Description

:= Assignment expression

lambda Lambda expression

if – else Conditional expression

or Boolean OR

and Boolean AND

not x Boolean NOT

in, not in, is, is not, <, <=, >, >=, !=, == Comparisons, including membership te

| Bitwise OR

^ Bitwise XOR

& Bitwise AND

<<, >> Shifts

+, - Addition and subtraction

*, @, /, //, % Multiplication, matrix multiplication, d


+x, -x, ~x Positive, negative, bitwise NOT

** Exponentiation

await x Await expression

x[index], x[index:index], x(arguments...), x.attribute Subscription, slicing, call, attribute refe

(expressions...),[expressions...], {key: value...}, {expressions...} Binding or parenthesized expression, li

if..elif..else
The if-elif-else statement is used to conditionally execute a statement or a block
of statements. Conditions can be true or false, execute one thing when the
condition is true, something else when the condition is false.

Contents:

 if statement

 if .. else statement

 if .. elif .. else statement

 Nested if .. else

 Use the and operator in an if statement

 Use the in operator in an if statement

 Write an if-else in a single line of code

 Define a negative if
if statement
The Python if statement is same as it is with other programming languages. It
executes a set of statements conditionally, based on the value of a logical
expression.

Here is the general form of a one way if statement.

Syntax:
if expression :
    statement_1
    statement_2
    ....
In the above case, expression specifies the conditions which are based on
Boolean expression. When a Boolean expression is evaluated it produces either
a value of true or false. If the expression evaluates true the same amount of
indented statement(s) following if will be executed. This group of the statement(s)
is called a block.

if .. else statement
In Python if .. else statement, if has two blocks, one following the expression and
other following the else clause. Here is the syntax.

Syntax:

if expression :
    statement_1
    statement_2
    ....
else :
   statement_3
   statement_4
   ....
In the above case if the expression evaluates to true the same amount of
indented statements(s) following if will be executed and if the expression
evaluates to false the same amount of indented statements(s) following else will
be executed. See the following example. The program will print the second print
statement as the value of a is 10.
a=10

if(a>10):

print("Value of a is greater than 10")

else :

print("Value of a is 10")

Copy
Output:
Value of a is 10
Flowchart:

if .. elif .. else statement


Sometimes a situation arises when there are several conditions. To handle the
situation Python allows adding any number of elif clause after an if and before an
else clause. Here is the syntax.
Syntax:

if expression1 :
    statement_1
    statement_2
    ....

elif expression2 :
   statement_3
   statement_4
   ....
elif expression3 :
   statement_5
   statement_6
   ....................
else :
   statement_7
   statement_8
In the above case Python evaluates each expression (i.e. the condition) one by
one and if a true condition is found the statement(s) block under that expression
will be executed. If no true condition is found the statement(s) block under else
will be executed. In the following example, we have applied if, series of elif and
else to get the type of a variable.
var1 = 1+2j

if (type(var1) == int):

print("Type of the variable is Integer")

elif (type(var1) == float):

print("Type of the variable is Float")

elif (type(var1) == complex):

print("Type of the variable is Complex")

elif (type(var1) == bool):

print("Type of the variable is Bool")

elif (type(var1) == str):

print("Type of the variable is String")

elif (type(var1) == tuple):


print("Type of the variable is Tuple")

elif (type(var1) == dict):

print("Type of the variable is Dictionaries")

elif (type(var1) == list):

print("Type of the variable is List")

else:

print("Type of the variable is Unknown")

Copy
Output:
Type of the variable is Complex
Flowchart:
 

Nested if .. else statement


In general nested if-else statement is used when we want to check more than
one conditions. Conditions are executed from top to bottom and check each
condition whether it evaluates to true or not. If a true condition is found the
statement(s) block associated with the condition executes otherwise it goes to
next condition. Here is the syntax :

Syntax:

if expression1 :
    if expression2 :
     statement_3
     statement_4
   ....
   else :
    statement_5
    statement_6
   ....
else :
  statement_7
  statement_8
In the above syntax expression1 is checked first, if it evaluates to true then the
program control goes to next if - else part otherwise it goes to the last else
statement and executes statement_7, statement_8 etc.. Within the if - else if
expression2 evaluates true then statement_3, statement_4 will execute
otherwise statement_5, statement_6 will execute. See the following example.
age = 38

if (age >= 11):

print ("You are eligible to see the Football match.")

if (age <= 20 or age >= 60):

print("Ticket price is $12")

else:
print("Tic kit price is $20")

else:

print ("You're not eligible to buy a ticket.")

Copy
Output :
You are eligible to see the Football match.
Tic kit price is $20
In the above example age is set to 38, therefore the first expression (age >= 11)
evaluates to True and the associated print statement prints the string "You are
eligible to see the Football match". There after program control goes to next if
statement and the condition ( 38 is outside <=20 or >=60) is matched and prints
"Tic kit price is $12".

Flowchart:
 

Use the and operator in an if statement


#create two boolean objects

x = False

y = True
#The validation will be True only if all the expressions generate a value True

if x and y:

print('Both x and y are True')

else:

print('x is False or y is False or both x and y are False')

Copy
Output:
x is False or y is False or both x and y are False

Use the in operator in an if statement


#create a string

s = 'jQuery'

#create a list

l = ['JavaScript', 'jQuery', 'ZinoUI']

# in operator is used to replace various expressions that use the or operator

if s in l:

print(s + ' Tutorial')

#Alternate if statement with or operator

if s == 'JavaScript' or s == 'jQuery' or s == 'ZinoUI':

print(s + ' Tutorial')

Copy
Output:
jQuery Tutorial
jQuery Tutorial
Write an if-else in a single line of code
#create a integer

n = 150

print(n)

#if n is greater than 500, n is multiplied by 7, otherwise n is divided by 7

result = n * 7 if n > 500 else n / 7

print(result)

Copy
Output:
150
21.428571428571427

Define a negative if
If a condition is true the not operator is used to reverse the logical state, then
logical not operator will make it false.
#create a integer

x = 20

print(x)

#uses the not operator to reverse the result of the logical expression

if not x == 50:

print('the value of x different from 50')

else:

print('the value of x is equal to 50')


Copy
Output:
20
the value of x different from 50

Python for loop


Last update on February 28 2020 12:12:41 (UTC/GMT +8 hours)

for loop
Like most other languages, Python has for loops, but it differs a bit from other like
C or Pascal. In Python for loop is used to iterate over the items of any sequence
including the Python list, string, tuple etc. The for loop is also used to access
elements from a container (for example list, string, tuple) using built-in function
range().

Syntax:
for variable_name in sequence :
    statement_1
    statement_2
    ....
Parameter:

Name Description

variable_name It indicates target variable which will set a new value for each iteration of the loop.

sequence A sequence of values that will be assigned to the target variable variable_name. Values a
built-in function range().

statement_1, Block of program statements.


statement_2 .....

Example: Python for loop


>>> #The list has four elements, indices start at 0 and end at 3

>>> color_list = ["Red", "Blue", "Green", "Black"]

>>> for c in color_list:

print(c)

Red

Blue

Green

Black

>>>

Copy

In the above example color_list is a sequence contains a list of various color


names. When the for loop executed the first item (i.e. Red) is assigned to the
variable c. After this, the print statement will execute and the process will
continue until we reach the end of the list.

Python for loop and range() function


The range() function returns a list of consecutive integers. The function has one,
two or three parameters where last two parameters are optional. It is widely used
in for loops. Here is the syntax.
range(a)
range(a,b)
range(a,b,c)
range(a) : Generates a sequence of numbers from 0 to a, excluding a,
incrementing by 1.

Syntax:
for <variable> in range(<number>):
Example:
>>> for a in range(4):
print(a)

>>>

Copy

range(a,b): Generates a sequence of numbers from a to b excluding b,


incrementing by 1.

Syntax:
for "variable" in range("start_number", "end_number"):
Example:
>>> for a in range(2,7):

print(a)

>>>

Copy

range(a,b,c): Generates a sequence of numbers from a to b excluding b,


incrementing by c.

Example:
>>> for a in range(2,19,5):
print(a)

12

17

>>>

Copy

Python for loop: Iterating over tuple, list, dictionary


Example: Iterating over tuple

The following example counts the number of even and odd numbers from a
series of numbers.
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) # Declaring the tuple

count_odd = 0

count_even = 0

for x in numbers:

if x % 2:

count_odd+=1

else:

count_even+=1

print("Number of even numbers :",count_even)

print("Number of odd numbers :",count_odd)

Copy

Output:
Number of even numbers:4
Number of odd numbers: 5
In the above example a tuple named numbers is declared which holds the
integers 1 to 9.

The best way to check if a given number is even or odd is to use the modulus
operator (%).
The operator returns the remainder when dividing two numbers.
Modulus of 8 % 2 returns 0 as 8 is divided by 2, therefore 8 is even and modulus
of 5 % 2 returns 1 therefore 5 is odd.

The for loop iterates through the tuple and we test modulus of x % 2 is true or
not, for every item in the tuple and the process will continue until we rich the end
of the tuple.
When it is true count_even increase by one otherwise count_odd is increased by
one.
Finally, we print the number of even and odd numbers through print statements.

Example: Iterating over list

In the following example for loop iterates through the list "datalist" and prints
each item and its corresponding Python type.
datalist = [1452, 11.23, 1+2j, True, 'w3resource', (0, -1), [5, 12],

{"class":'V', "section":'A'}]

for item in datalist:

print ("Type of ",item, " is ", type(item))

Copy

Output:
Type of 1452 is <class 'int'>
Type of 11.23 is <class 'float'>
Type of (1+2j) is <class 'complex'>
Type of True is <class 'bool'>
Type of w3resource is <class 'str'>
Type of (0, -1) is <class 'tuple'>
Type of [5, 12] is <class 'list'>
Type of {'section': 'A', 'class': 'V'} is <class 'dict'>
Example: Iterating over dictionary
In the following example for loop iterates through the dictionary "color" through its
keys and prints each key.
>>> color = {"c1": "Red", "c2": "Green", "c3": "Orange"}

>>> for key in color:

print(key)

c2

c1

c3

>>>

Copy

Following for loop iterates through its values :


>>> color = {"c1": "Red", "c2": "Green", "c3": "Orange"}

>>> for value in color.values():

print(value)

Green

Red

Orange

>>>

Copy

You can attach an optional else clause with for statement, in this case, syntax will
be -
for variable_name in sequence :
    statement_1
    statement_2
    ....
else :
    statement_3
    statement_4
    ....
The else clause is only executed after completing the for loop. If a break
statement executes in first program block and terminates the loop then the else
clause does not execute

Python while loop


Last update on February 28 2020 12:09:43 (UTC/GMT +8 hours)

While loop
Loops are used to repeatedly execute a block of program statements. The basic
loop structure in Python is while loop. Here is the syntax.

Syntax:
while (expression) :
    statement_1
    statement_2
    ....

The while loop runs as long as the expression (condition) evaluates to True and
execute the program block. The condition is checked every time at the beginning
of the loop and the first time when the expression evaluates to False, the loop
stops without executing any remaining statement(s). The following example
prints the digits 0 to 4 as we set the condition x < 5.
x = 0;

while (x < 5):

print(x)

x += 1

Copy

Output:
0
1
2
3
4
One thing we should remember that a while loop tests its condition before the
body of the loop (block of program statements) is executed. If the initial test
returns false, the body is not executed at all. For example the following code
never prints out anything since before executing the condition evaluates to false.
x = 10;

while (x < 5):

print(x)

x += 1

Copy

Flowchart:

The following while loop is an infinite loop, using True as the condition:
x = 10;

while (True):

print(x)

x += 1

Copy

Flowchart:
 

Python: while and else statement


There is a structural similarity between while and else statement. Both have a
block of statement(s) which is only executed when the condition is true. The
difference is that block belongs to if statement executes once whereas block
belongs to while statement executes repeatedly.

You can attach an optional else clause with while statement, in this case, syntax
will be -
while (expression) :
    statement_1
    statement_2
    ......
else :
    statement_3
    statement_4
    ......

The while loop repeatedly tests the expression (condition) and, if it is true,
executes the first block of program statements. The else clause is only executed
when the condition is false it may be the first time it is tested and will not execute
if the loop breaks, or if an exception is raised. If a break statement executes in
first program block and terminates the loop then the else clause does not
execute. In the following example, while loop calculates the sum of the integers
from 0 to 9 and after completing the loop, else statement executes.

x = 0;

s = 0

while (x < 10):

s = s + x

x = x + 1

else :

print('The sum of first 9 integers : ',s)

Copy

Output:
The sum of first 9 integers: 45
Flowchart:

 
Example: while loop with if-else and break statement
x = 1;

s = 0

while (x < 10):

s = s + x

x = x + 1

if (x == 5):

break

else :

print('The sum of first 9 integers : ',s)

print('The sum of ',x,' numbers is :',s)

Copy

Output:
The sum of 5 numbers is : 10
In the above example the loop is terminated when x becomes 5. Here we use
break statement to terminate the while loop without completing it, therefore
program control goes to outside the while - else structure and execute the next
print statement.

Flowchart:
Python break, continue statement
Last update on February 28 2020 12:05:29 (UTC/GMT +8 hours)

break statement
The break statement is used to exit a for or a while loop. The purpose of this
statement is to end the execution of the loop (for or while) immediately and the
program control goes to the statement after the last statement of the loop. If there
is an optional else statement in while or for loop it skips the optional clause also.
Here is the syntax.

Syntax:

while (expression1) :
   statement_1
   statement_2
   ......
   if expression2 :
   break
for variable_name in sequence :
   statement_1
   statement_2
   if expression3 :
     break
Example: break in for loop

In the following example for loop breaks when the count value is 5. The print
statement after the for loop displays the sum of first 5 elements of the tuple
numbers.
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) # Declaring the tuple

num_sum = 0

count = 0

for x in numbers:

num_sum = num_sum + x

count = count + 1

if count == 5:

break

print("Sum of first ",count,"integers is: ", num_sum)

Copy

Output:
Sum of first 5 integers is: 15
Example: break in while loop
In the following example while loop breaks when the count value is 5. The print
statement after the while loop displays the value of num_sum (i.e. 0+1+2+3+4).
num_sum = 0

count = 0

while(count<10):

num_sum = num_sum + count

count = count + 1

if count== 5:

break

print("Sum of first ",count,"integers is: ", num_sum)

Copy

Output:
Sum of first 5 integers is : 10

continue statement
The continue statement is used in a while or for loop to take the control to the top
of the loop without executing the rest statements inside the loop. Here is a simple
example.
for x in range(7):

if (x == 3 or x==6):

continue

print(x)

Copy

Output:
0
1
2
4
5
In the above example, the for loop prints all the numbers from 0 to 6 except 3
and 6 as the continue statement returns the control of the loop to the top

Python Bytes, Bytearray


Last update on February 28 2020 12:06:43 (UTC/GMT +8 hours)

Bytes, Bytearray
Python supports a range of types to store sequences. There are six sequence
types: strings, byte sequences (bytes objects), byte arrays (bytearray objects),
lists, tuples, and range objects.

Strings contain Unicode characters. Their literals are written in single or double
quotes : 'python', "data". Bytes and bytearray objects contain single bytes – the
former is immutable while the latter is a mutable sequence. Bytes objects can be
constructed the constructor, bytes(), and from literals; use a b prefix with normal
string syntax: b'python'. To construct byte arrays, use the bytearray() function.

Contents

 Bytes literals

 bytes() and bytearray() functions

 Create a bytes object in Python

 Convert bytes to string

 Convert hex string to bytes

 Numeric code representing a character of a bytes object in Python

 Define a mapping table characters for use with a bytes object in Python

 Convert bytes to hex in Python


 How to get the character from the numeric code in bytes objects in Python

 Determine the length of a bytes object in Python

 Use the operators + and * with bytes objects in Python

 How to get a byte from a bytes object in Python

 Create a bytearray object

 Difference between bytes and bytearray object in Python

 Convert a bytes to bytearray

 Slice of a bytes object in Python

 Difference between bytes and string object

Bytes literals
bytesliteral ::= bytesprefix(shortbytes | longbytes)
bytesprefix ::= "b" | "B" | "br" | "Br" | "bR" | "BR"
shortbytes ::= "'" shortbytesitem* "'" | '"' shortbytesitem*
'"'
longbytes ::= "'''" longbytesitem* "'''" | '"""'
longbytesitem* '"""'
shortbytesitem ::= shortbyteschar | bytesescapeseq
longbytesitem ::= longbyteschar | bytesescapeseq
shortbyteschar ::= <any ASCII character except "\" or newline or
the quote>
longbyteschar ::= <any ASCII character except "\">
bytesescapeseq ::= "\" <any ASCII character>

bytes() and bytearray() functions


bytes() function:

Return a new "bytes" object, which is an immutable sequence of small integers in


the range 0 <= x < 256, print as ASCII characters when displayed. bytes is an
immutable version of bytearray – it has the same non-mutating methods and the
same indexing and slicing behavior.
Syntax:
bytes([source[, encoding[, errors]]])
bytearray() function :

Return a new array of bytes. The bytearray type is a mutable sequence of


integers in the range 0 <= x < 256. It has most of the usual methods of mutable
sequences, described in Mutable Sequence Types, as well as most methods that
the bytes type has, see Bytes and Byte Array Methods.

Syntax:
bytearray([source[, encoding[, errors]]])
The optional source parameter can be used to initialize the array in a few
different ways:

 If it is a string, you must also give the encoding (and optionally, errors) parameters;
bytearray() then converts the string to bytes using str.encode().

 If it is an integer, the array will have that size and will be initialized with null bytes.

 If it is an object conforming to the buffer interface, a read-only buffer of the object will be
used to initialize the bytes array.

 If it is iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as
the initial contents of the array.

Without an argument, an array of size 0 is created.

Create a bytes object in Python


Example-1 :

Code :
>>> x = b"Bytes objects are immutable sequences of single bytes"

>>> print(x)

b'Bytes objects are immutable sequences of single bytes'

>>>
Copy
Example-2:

Code:
#triple single or double quotes allows multiple lines

x = b'''Python Tutorial,

Javascript Tutorial,

MySQL Tutorial'''

print(x)

Copy
Output:
b'Python Tutorial,\nJavascript Tutorial,\nMySQL Tutorial'
Example-3 :

Code :
#created from a iterable of ints, string, bytes or buffer objects.

x = bytes('Python, bytes', 'utf8')

print(x)

Copy
Output:
b'Python, bytes'

Convert bytes to string


Example-1:

Code:
#create a bytes object

x = b'El ni\xc3\xb1o come camar\xc3\xb3n'

print(x)
Copy
Output:
b'El ni\xc3\xb1o come camar\xc3\xb3n'
Example-2:

Code:
# create a string using the decode() method of bytes.

#This method takes an encoding argument, such as UTF-8, and optionally an errors
argument.

x = b'El ni\xc3\xb1o come camar\xc3\xb3n'

s = x.decode()

print(type(s))

print(s)

Copy
Output:

El niño come camarón


Example-3:

Code:
#create a bytes object encoded using 'cp855'

x = b'\xd8\xe1\xb7\xeb\xa8\xe5 \xd2\xb7\xe1'

print(x)

#return a string using decode 'cp855'

y = x.decode('cp855')

print(y)

Copy
Output:
b'\xd8\xe1\xb7\xeb\xa8\xe5 \xd2\xb7\xe1'
привет мир
Convert hex string to bytes
Example-1:

Code :
#create a string with hexadecimal data

x = '45678c6c56f205876f72c64'

print(x)

Copy
Output:
45678c6c56f205876f72c64
Example-2:

Code :
#this class method returns a bytes object, decoding the given string object.

#the string must contain two hexadecimal digits per byte.

x = '45678c6c56f205876f72c64'

y = bytes.fromhex(x)

Copy
Output:
b'.\xf0\xf1\xf2'

Numeric code representing a character of a bytes object in

Python
Example-1:

Code:
#return an integer representing the Unicode code point of that character.
x = ord(b'm')

print(x)

Copy
Output:
109
Example-2:

Code:
#create a bytes object

y = b'Python bytes'

#generates a list of codes from the characters of bytes

z = list(y)

print(z)

Copy
Output:
[80, 121, 116, 104, 111, 110, 32, 98, 121, 116, 101, 115]

Define a mapping table characters for use with a bytes

object in Python
Example-1:

Code:
#create a str

x = b'Python mapping table characters'

print(x)

Copy
Output:
b'Python mapping table characters'
Example-2:

Code:
b_table = bytes.maketrans(b'abcdef', b'uvwxyz')

print(type(b_table))

print(b_table)

Copy
Output:
<class 'bytes'>

b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\
x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%
&\'()*+,-./0123456789:;<=>?
@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`uvwxyzghijklmnopqrstuvwxyz{|}~\
x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x
8f\x
90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa
0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0
\xb1\
xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\x
c2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd
2\xd3
\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\
xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\x
f4\xf
5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff'
Example-3:

Code:
b_table = bytes.maketrans(b'abcdef', b'uvwxyz')

str = 'Write a Python function to find a distinct pair of numbers whose product is
odd from a sequence of integer values.'

b_new = str.translate(b_table)

print(b_new)

Copy
Output:
Writy u Python zunwtion to zinx u xistinwt puir oz numvyrs whosy
proxuwt is oxx zrom u syquynwy oz intygyr vuluys.

Convert bytes to hex in Python


>>> import binascii

>>> binascii.hexlify("Python".encode("utf8"))

b'507974686f6e'

>>> binascii.unhexlify(_).decode("utf8")

'Python'

>>>

Copy

How to get the character from the numeric code in bytes

objects in Python
>>> #this method return a single character based on the integer value.

>>> x = chr(60)

>>> print(x)

<

>>> x = chr(50)

>>> print(x)

>>> #create a list with integers in the range 0 through 255

>>> y = [70, 111, 106, 94, 101, 100, 22, 95, 105, 22, 91, 87, 125, 135]

>>> print(y)

[70, 111, 106, 94, 101, 100, 22, 95, 105, 22, 91, 87, 125, 135]

>>> #create a bytes object from a list of integers in the range 0 through 255.
>>> z = bytes(y)

>>> print(z)

b'Foj^ed\x16_i\x16[W}\x87'

>>>

Copy

Determine the length of a bytes object in Python


>>> #create a string

>>> x = "Python, Bytes"

>>> print(x)

Python, Bytes

>>> #know the length of the string using the len() function

>>> print(len(x))

13

>>> #create a bytes object

>>> y = bytes(x, "utf8")

>>> print(y)

b'Python, Bytes'

>>> #know the length of the bytes object using the len() function

>>> print(len(y))

13

>>>

Copy

Use the operators + and * with bytes objects in Python


>>> #create a bytes object

>>> x = b"byte 213"

>>> print(x)

b'byte 213'

>>> #The * operator allow repeat the characters of a bytes object

>>> print(x * 5)

b'byte 213byte 213byte 213byte 213byte 213'

>>> #create two bytes objects.

>>> x1 = bytes([70, 111, 106, 94, 101, 100, 22, 95, 105, 22, 91, 87, 125, 135])

>>> x2 = b"Python"

>>> #The + operator allow create a new bytes object joining two or more bytes.

>>> x = x1 + x2

>>> print(x)

b'Foj^ed\x16_i\x16[W}\x87Python'

>>> #create a bytes object combining operators

>>> x = b"Python" + b"Bytes" * 3 + b"$"

>>> print(x)

b'PythonBytesBytesBytes$'

>>>

Copy

How to get a byte from a bytes object in Python?


>>> y = [80, 121, 116, 104, 111, 110, 32, 105, 115, 32, 101, 97, 115, 121]

>>> print(y)

[80, 121, 116, 104, 111, 110, 32, 105, 115, 32, 101, 97, 115, 121]

>>> #create a bytes object

>>> x1 = bytes([70, 111, 106, 94, 101, 100, 22, 95, 105, 22, 91, 87, 125, 135])
>>> print(x1)

b'Foj^ed\x16_i\x16[W}\x87'

>>> #is similar to the handling of lists, the index is defined in brackets

>>> x = y[3]

>>> print(x)

104

>>> print(chr(x))

>>> #can also use negative indices to get a byte from bytes object

>>> x = [-8]

>>> print(x)

[-8]

>>> x = y[-8]

>>> print(x)

110

>>> print(chr(x))

>>>

Copy

Create a bytearray object in Python


>>> #create a bytearray from a bytes object

>>> x = bytearray(b"Python Bytes")

>>> print(x)

bytearray(b'Python Bytes')

>>> #create a bytearray from a string defining the standard of coding

>>> x = bytearray("Python Bytes", "utf8")


>>> print(x)

bytearray(b'Python Bytes')

>>> #create a bytearray from a list of integers in the range 0 through 255

>>> x = bytearray([94, 91, 101, 125, 111, 35, 120, 101, 115, 101, 200])

>>> print(x)

bytearray(b'^[e}o#xese\xc8')

>>>

Copy

Difference between bytes and bytearray object in Python


>>> #bytearray objects are a mutable counterpart to bytes objects

>>> x = bytearray("Python bytearray", "utf8")

>>> print(x)

bytearray(b'Python bytearray')

>>> #can remove items from the bytes

>>> del x[11:15]

>>> print(x)

bytearray(b'Python bytey')

>>> #can add items from the bytes

>>> x[11:15] = b" object"

>>> print(x)

bytearray(b'Python byte object')

>>> #can use the methods of mutable type iterable objects as the lists

>>> x.append(45)

>>> print(x)

bytearray(b'Python byte object-')

>>>
Copy

Convert a bytes to bytearray


>>> #create a bytes object from a list of integers in the range 0 through 255

>>> x = bytes([105, 100, 107, 112, 132, 118, 107, 112, 200])

>>> print(x)

b'idkp\x84vkp\xc8'

>>> #generates a new array of bytes from a bytes object

>>> x1 = bytearray(x)

>>> print(x1)

bytearray(b'idkp\x84vkp\xc8')

>>>

Copy

Slice of a bytes object in Python


>>> #create a bytes object

>>> x = b"Python slice"

>>> print(x)

b'Python slice'

>>> #b[start:stop] the start index is inclusive and the end index is exclusive.

>>> x1 = x[2:6]

>>> print(x1)

b'thon'

>>> #if the start index isn't defined, is starts from the beginning

>>> x1 = x[-5:]

>>> print(x1)
b'slice'

>>> #if the end index isn't defined, it goes until the end

>>> x1 = x[:4]

>>> print(x1)

b'Pyth'

>>> #if neither is defined, returns the full bytes object

>>> x1 = x[:]

>>> print(x1)

b'Python slice'

>>>

Copy

Difference between bytes and string object


>>> # bytes objects are immutable sequences of integers, each value in the sequence

>>> # string objects are immutable sequences of unicode characters.

>>> x = "Python String"

>>> y = b"Python String"

>>> print(x)

Python String

>>> print(y)

b'Python String'

>>> # Found in unicode representation of characters but not in ascii

>>> x = "Python"

>>> y = bytes("Python", "utf8")

>>> print(x)

Python

>>> print(y)
Python Regular Expression
Last update on February 28 2020 12:15:20 (UTC/GMT +8 hours)

Regular Expression
A regular expression (or RE) specifies a set of strings that matches it; the
functions in this module let you check if a particular string matches a given
regular expression (or if a given regular expression matches a particular string,
which comes down to the same thing).

Contents:

 Compare HTML tags

 re.findall() match string

 Group Comparison

 Non capturing group

 Back Reference

 Named Grouping (?P<name>)

 Substitute String

 Look around

 Match common username or password

 Match hex color value

 Match email

 Match URL

 Match IP address

 Match Mac address

 Lexer

 Python Regular Expression - Exercises, Practice, Solution


The following table provides a list and description of the special pattern matching
characters that can be used in regular expressions.

Special Description
characters

. (Dot.) In the default mode, this matches any character except a newline. If the DOTALL flag
including a newline.

^ (Caret.) Matches the beginning of the string or line. For example /^A/ does not match the 'A'
"Articles of life"

$ Matches the end of the string or line. For example, /e$/ does not match the 't' in "exact", but d

* Matches the previous character 0 or more times. For example, /bo*/ matches 'boo' in "A boot
nothing in "A going concern".

+ Matches the previous character 1 or more times. For example, /a+/ matches the 'a' in "Daniel

? Matches the previous character 0 or 1 time. For example, /r?eu?/ matches the 're' in "w3resou

*?, +?, ?? The '*', '+', and '?' qualifiers are all greedy; they match as much text as possible. Sometimes t
matched against '<a> b <c>', it will match the entire string, and not just '<a>'. Adding ? after
non-greedy or minimal fashion; as few characters as possible will be matched. Using the RE

{m} Specifies that exactly m copies of the previous RE should be matched; fewer matches cause t
example, b{5} will match exactly five 'b' characters, but not four.

{m,n} Causes the resulting RE to match from m to n repetitions of the preceding RE. For example, 
Omitting m specifies a lower bound of zero, and omitting n specifies an infinite upper bound
thousand 'a' characters followed by a 'b', but not 'aaab'.

{m,n}? Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to
non-greedy version of the previous qualifier. For example, on the 6-character string 'aaaaaa', 
while a{3,5}? will only match 3 characters.

\ Either escapes special characters (permitting you to match characters like '*', '?', and s
special sequences are discussed below.

[] Used to indicate a set of characters. In a set:

 Characters can be listed individually, e.g. [amk] will match 'a', 'm', or 'k'.

 Ranges of characters can be indicated by giving two characters and separating them by a '-', for ex
[0-5][0-9] will match all the two-digits numbers from 00 to 59, and [0-9A-Fa-f] will match any he
placed as the first or last character (e.g. [-a] or [a-]), it will match a literal '-'.

 Special characters lose their special meaning inside sets. For example, [(+*)] will match any of th

 Character classes such as \w or \S (defined below) are also accepted inside a set, although the cha
LOCALE mode is in force.

 Characters that are not within a range can be matched by complementing the set. If the first chara
the set will be matched. For example, [^5] will match any character except '5', and [^^] will match
it’s not the first character in the set.

 To match a literal ']' inside a set, precede it with a backslash, or place it at the beginning of the set
match a parenthesis.

| A|B, where A and B can be arbitrary REs, creates a regular expression that will match either
separated by the '|' in this way. This can be used inside groups (see below) as well.

(...) Matches whatever regular expression is inside the parentheses, and indicates the start and end
retrieved after a match has been performed, and can be matched later in the string with the \n
match the literals '(' or ')', use \( or \), or enclose them inside a character class: [(], [)].

(?...) This is an extension notation (a '?' following a '(' is not meaningful otherwise). The first chara
and further syntax of the construct is. Extensions usually do not create a new group; (?P<nam
Following are the currently supported extensions.

(?aiLmsux) (One or more letters from the set 'a', 'i', 'L', 'm', 's', 'u', 'x'.) The group matches the empty strin
(ASCII-only matching), re.I (ignore case), re.L (locale dependent), re.M (multi-line), re.S (do
re.X (verbose), for the entire regular expression.

(?:...) A non-capturing version of regular parentheses. Matches whatever regular expression is insid
by the group cannot be retrieved after performing a match or referenced later in the pattern.
(?imsx-imsx:...) (Zero or more letters from the set 'i', 'm', 's', 'x', optionally followed by '-' followed by one or
or removes the corresponding flags: re.I (ignore case), re.M (multi-line), re.S (dot matches al
expression.

(?P<name>...) Similar to regular parentheses, but the substring matched by the group is accessible vi
names must be valid Python identifiers, and each group name must be defined only on
group is also a numbered group, just as if the group were not named.

Named groups can be referenced in three contexts. If the pattern is (?P<quote>['"]).*?


with either single or double quotes):

Context of reference to group “quote” W

in the same pattern itself

when processing match object m

in a string passed to the repl argument of re.sub()

(?P=name) A backreference to a named group; it matches whatever text was matched by the earlier grou

(?#...) A comment; the contents of the parentheses are simply ignored.

(?=...) Matches if ... matches next, but doesn’t consume any of the string. This is called a lookahead
match 'Isaac ' only if it’s followed by 'Asimov'.

(?!...) Matches if ... doesn’t match next. This is a negative lookahead assertion. For example, Isaac
followed by 'Asimov'.

(?<=...) Matches if the current position in the string is preceded by a match for ... that ends at
positive lookbehind assertion. (?<=abc)def will find a match in 'abcdef', since the look
check if the contained pattern matches.
>>> import re
>>> m = re.search('(?<=abc)def', 'abcdef')
>>> m.group(0)
'def'
This example looks for a word following a hyphen:
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'

(?<!...) Matches if the current position in the string is not preceded by a match for .... This is called a
positive lookbehind assertions, the contained pattern must only match strings of some fixed l
lookbehind assertions may match at the beginning of the string being searched.

(?(id/name)yes- Will try to match with yes-pattern if the group with given id or name exists, and with no-patt
pattern|no- be omitted. For example, (<)?(\w+@\w+(?:\.\w+)+)(?(1)>|$) is a poor email matching pattern
pattern) well as 'user@host.com', but not with '<user@host.com' nor 'user@host.com>'. The special s
list below. If the ordinary character is not an ASCII digit or an ASCII letter, then the resultin
example, \$ matches the character '$'.

\number Matches the contents of the group of the same number. Groups are numbered starting from 1
55', but not 'thethe' (note the space after the group). This special sequence can only be used to
digit of number is 0, or number is 3 octal digits long, it will not be interpreted as a group mat
number. Inside the '[' and ']' of a character class, all numeric escapes are treated as characters

\A Matches only at the start of the string.

\b Matches the empty string, but only at the beginning or end of a word. A word is defin

\B Matches the empty string, but only when it is not at the beginning or end of a word. This mea
but not 'py', 'py.', or 'py!'. \B is just the opposite of \b, so word characters in Unicode patterns
although this can be changed by using the ASCII flag. Word boundaries are determined by th

\d Matches any character which is a digit. Equivalent to [0-9]. For example, /\d/ or /[0-9]
example."

\D Matches any character which is not a decimal digit. This is the opposite of \d. If the ASCII fl
9] (but the flag affects the entire regular expression, so in such cases using an explicit [^0-9]

\s Matches any white space character (including tab, new line, carriage return, form feed
For example, /\s\w*/ matches ' apple' in "An apple."
Matches characters considered whitespace in the ASCII character set; this is equivalen

\S Matches any character which is not a whitespace character. This is the opposite of \s. If the A
of [^ \t\n\r\f\v] (but the flag affects the entire regular expression, so in such cases using an ex

\w Matches characters considered alphanumeric in the ASCII character set; this is equiva
is used, matches characters considered alphanumeric in the current locale and the und

\W Matches any non-word character, equivalent to [^A-Za-z0-9_]. For example, /\W/ or /

\Z Matches only at the end of the string.

Compare HTML tags :

tag type format exampl

open tag <[^/>][^>]*> <a>, <ta

close tag </[^>]+> </p>, <

self close <[^/>]+/> <br />

all tag <[^>]+> <br />,

# open tag

>>> import re

>>> re.search('<[^/>][^>]*>', '<table>') != None

True

>>> import re

>>> re.search('<[^/>][^>]*>', '<a href="#label">') != None

True

>>> import re
>>> re.search('<[^/>][^>]*>', '<img src="/img">') != None

True

>>> import re

>>> re.search('<[^/>][^>]*>', '</table>') != None

False

# close tag

>>> import re

>>> re.search('</[^>]+>', '</table>') != None

True

# self close

>>> import re

>>> re.search('<[^/>]+/>', '<br />') != None

True

Copy
re.findall() match string :
# split all string

>>> import re

>>> source = "split all string"

>>> re.findall('[\w]+', source)

['split', 'all', 'string']

# parsing python.org website

>>> import urllib

>>> import re

>>> x = urllib.urlopen('https://www.w3resource.org')

>>> html = x.read()


>>> x.close()

>>> print("open tags")

open tags

>>> re.findall('<[^/>][^>]*>', html)[0:2]

['<!doctype html>', '<!-[if lt IE 7]>']

>>> print("close tags")

close tags

>>> re.findall('</[^>]+>', html)[0:2]

['</script>', '</title>']

>>> print("self-closing tags")

Copy
Group Comparison :
# (...) group a regular expression

>>> import re

>>> mon = re.search(r'(\d{4})-(\d{2})-(\d{2})', '2018-09-01')

>>> mon

<_sre.SRE_Match object at 0x019A72F0>

>>> mon.groups()

('2018', '09', '01')

>>> mon.group()

'2018-09-01')

>>> mon.group(1)

'2018'

>>> mon.group(2)

'09'

>>> mon.group(3)

'01'
# Nesting groups

>>> import re

>>> mon = re.search(r'(((\d{4})-\d{2})-\d{2})', '2018-09-01')

>>> mon.groups()

('2018-09-01', '2018-09', '2018')

>>> mon.group()

'2018-09-01'

>>> mon.group(1)

'2018-09-01'

>>> mon.group(2)

'2018-09'

>>> mon.group(3)

'2018'

Copy
Non capturing group :
# non capturing group

>>> import re

>>> url = 'http://w3resource.com/'

>>> mon = re.search('(?:http|ftp)://([^/\r\n]+)(/[^\r\n]*)?', url)

>>> mon.groups()

('w3resource.com', '/')

# capturing group

>>> import re

>>> mon = re.search('(http|ftp)://([^/\r\n]+)(/[^\r\n]*)?', url)

>>> mon.groups()

('http', 'w3resource.com', '/')


Copy
Back Reference :
# compare 'xx', 'yy'

>>> import re

>>> re.search(r'([a-z])\1$','xx') != None

True

>>> import re

>>> re.search(r'([a-z])\1$','yy') != None

True

>>> import re

>>> re.search(r'([a-z])\1$','xy') != None

False

# compare open tag and close tag

>>> import re

>>> pattern = r'<([^>]+)>[\s\S]*?</\1>'

>>> re.search(pattern, '<bold> test </bold>') != None

True

>>> re.search(pattern, '<h1> test </h1>') != None

True

>>> re.search(pattern, '<bold> test </h1>') != None

False

Copy
Named Grouping (?P<name>) :
# group reference ``(?P<name>...)``

>>> import re

>>> pattern = '(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})'

>>> mon = re.search(pattern, '2018-09-01')


>>> mon.group('year')

'2018'

>>> mon.group('month')

'09'

>>> mon.group('day')

'01'

# back reference ``(?P=name)``

>>> import re

>>> re.search('^(?P<char>[a-z])(?P=char)','aa')

<_sre.SRE_Match object at 0x01A08660>

Copy
Substitute String :
# basic substitute

>>> import re

>>> res = "4x5y6z"

>>> re.sub(r'[a-z]',' ', res)

'4 5 6 '

# substitute with group reference

>>> import re

>>> date = r'2018-09-01'

>>> re.sub(r'(\d{4})-(\d{2})-(\d{2})',r'\2/\3/\1/',date)

'09/01/2018/'

# camelcase to underscore

>>> def convert(s):

... res = re.sub(r'(.)([A-Z][a-z]+)',r'\1_\2', s)


... return re.sub(r'([a-z])([A-Z])',r'\1_\2', res).lower()

...

>>> convert('SentenceCase')

'sentence_case'

>>> convert('SentenceSentenceCase')

'sentence_sentence_case'

>>> convert('SampleExampleHTTPServer')

'sample_example_http_server'

Copy
Look around :

notation compare direction

(?<=...) right to left

(?=...) left to right

(?!<...) right to left

(?!...) left to right

# basic

>>> import re

>>> re.sub('(?=\d{3})', ' ', '56789')

' 5 6 789'

>>> re.sub('(?!\d{3})', ' ', '56789')

'567 8 9 '

>>> re.sub('(?<=\d{3})', ' ', '56789')

'567 8 9 '
>>> re.sub('(?<!\d{3})', ' ', '56789')

' 5 6 789'

Copy
Match common username or password :
>>> import re

>>> re.match('^[a-zA-Z0-9-_]{3,16}$', 'Foo') is not None

True

>>> re.match('^\w|[-_]{3,16}$', 'Foo') is not None

True

Copy
Match hex color value :
>>> import re

>>> re.match('^#?([a-f0-9]{6}|[a-f0-9]{3})$', '#ff0000')

<_sre.SRE_Match object at 0x019E7720>

>>> re.match('^#?([a-f0-9]{6}|[a-f0-9]{3})$', '#000000')

<_sre.SRE_Match object at 0x019E77A0>

Copy
Match email :
>>> import re

>>> re.match('^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$',

'citi.world@example.com')

<_sre.SRE_Match object; span=(0, 22), match='citi.world@example.com'>

# or

>>> import re

>>> example = re.compile(r'''^([a-zA-Z0-9._%-]+@

[a-zA-Z0-9.-]+
\.[a-zA-Z]{2,4})*$''', re.X)

>>> example.match('citi.world@example.citi.com')

<_sre.SRE_Match object; span=(0, 27), match='citi.world@example.citi.com'>

>>> example.match('citi%world@example.citi.com')

<_sre.SRE_Match object; span=(0, 27), match='citi%world@example.citi.com'>

Copy
Match URL :
>>> import re

>>> example = re.compile(r'''^(https?:\/\/)? # match http or https

... ([\da-z\.-]+) # match domain

... \.([a-z\.]{2,6}) # match domain

... ([\/\w \.-]*)\/?$ # match api or file

... ''', re.X)

>>> example.match('www.yahoo.com')

<_sre.SRE_Match object; span=(0, 13), match='www.yahoo.com'>

>>> example.match('http://www.example')

<_sre.SRE_Match object; span=(0, 18), match='http://www.example'>

>>> example.match('http://www.example/w3r.html')

<_sre.SRE_Match object; span=(0, 27), match='http://www.example/w3r.html'>

>>> example.match('http://www.example/w3r!.html')

>>> example

re.compile('^(https?:\\/\\/)?\n([\\da-z\\.-]+)\n\\.([a-z\\.]
{2,6})\n([\\/\\w \\.-]*)\\/?$\n', re.VERBOSE)

Copy
Match IP address :

notation description

[1]?[0-9][0-9] Match 0-199 pattern


2[0-4][0-9] Match 200-249 pattern

25[0-5] Match 251-255 pattern

(?:...) Don't capture group

>>> import re

>>> example = re.compile(r'''^(?:(?:25[0-5]

... |2[0-4][0-9]

... |[1]?[0-9][0-9]?)\.){3}

... (?:25[0-5]

... |2[0-4][0-9]

... |[1]?[0-9][0-9]?)$''', re.X)

>>> example.match('192.168.1.1')

<_sre.SRE_Match object at 0x0134A608>

>>> example.match('255.255.255.0')

<_sre.SRE_Match object at 0x01938678>

>>> example.match('172.17.0.5')

<_sre.SRE_Match object at 0x0134A608>

>>> example.match('256.0.0.0') is None

True

Copy
Match Mac address :
>>> import random

>>> mac = [random.randint(0x00, 0x6b),

... random.randint(0x00, 0x6b),


... random.randint(0x00, 0x6b),

... random.randint(0x00, 0x6b),

... random.randint(0x00, 0x6b),

... random.randint(0x00, 0x6b)]

>>> mac = ':'.join(map(lambda x: "%02x" % x, mac))

>>> mac

'05:38:64:60:55:63'

>>> import re

>>> example = re.compile(r'''[0-9a-f]{2}([:])

... [0-9a-f]{2}

... (\1[0-9a-f]{2}){4}$''', re.X)

>>> example.match(mac) is not None

True

Copy
Lexer :
>>> import re

>>> from collections import namedtuple

>>> tokens = [r'(?P<NUMBER>\d+)',

r'(?P<PLUS>\+)',

r'(?P<MINUS>-)',

r'(?P<TIMES>\*)',

r'(?P<DIVIDE>/)',

r'(?P<WS>\s+)']

>>> lex = re.compile('|'.join(tokens))

>>> Token = namedtuple('Token', ['type', 'value'])

>>> def tokenize(text):

scan = lex.scanner(text)

return (Token(m.lastgroup, m.group())


for m in iter(scan.match, None) if m.lastgroup != 'WS')

>>> for _t in tokenize('9 + 5 * 2 - 7'):

print(_t)

Token(type='NUMBER', value='9')

Token(type='PLUS', value='+')

Token(type='NUMBER', value='5')

Token(type='TIMES', value='*')

Token(type='NUMBER', value='2')

Token(type='MINUS', value='-')

Token(type='NUMBER', value='7')

>>> tokens

['(?P<NUMBER>\\d+)', '(?P<PLUS>\\+)', '(?P<MINUS>-)', '(?P<TIMES>\\*)', '(?


P<DIVIDE>/)', '(?P<WS>\\s+)']

Python String
Last update on February 28 2020 12:15:43 (UTC/GMT +8 hours)

String
Python has a built-in string class named "str" with many useful features. String
literals can be enclosed by either single or double, although single quotes are
more commonly used.

Backslash escapes work the usual way within both single and double quoted
literals -- e.g. \n \' \". A double quoted string literal can contain single quotes
without any fuss (e.g. "I wouldn't be a painter") and likewise single quoted string
can contain double quotes.

A string literal can span multiple lines, use triple quotes to start and end them.
You can use single quotes too, but there must be a backslash \ at the end of
each line to escape the newline.

Contents :

 String commands

 Initialize string literals in Python

 Access character(s) from a string

 Python strings are immutable

 Python string concatenation

 Using '*' operator

 String length

 Traverse string with a while or for loop

 String slices

 Search a character in a string

 Python Data Types: String - Exercises, Practice, Solution

String: Commands
# Strips all whitespace characters from both ends.
<str> = <str>.strip()
# Strips all passed characters from both ends.
<str> = <str>.strip('<chars>')

# Splits on one or more whitespace characters.


<list> = <str>.split()
# Splits on 'sep' str at most 'maxsplit' times.
<list> = <str>.split(sep=None, maxsplit=-1)
# Splits on line breaks. Keeps them if 'keepends'.
<list> = <str>.splitlines(keepends=False)
# Joins elements using string as separator.
<str> = <str>.join(<coll_of_strings>)
# Checks if string contains a substring.
<bool> = <sub_str> in <str>
# Pass tuple of strings for multiple options.
<bool> = <str>.startswith(<sub_str>)
# Pass tuple of strings for multiple options.
<bool> = <str>.endswith(<sub_str>)
# Returns start index of first match or -1.
<int> = <str>.find(<sub_str>)
# Same but raises ValueError if missing.
<int> = <str>.index(<sub_str>)

# Replaces 'old' with 'new' at most 'count' times.


<str> = <str>.replace(old, new [, count])
# True if str contains only numeric characters.
<bool> = <str>.isnumeric()
# Nicely breaks string into lines.
<list> = textwrap.wrap(<str>, width)

 Also: 'lstrip()', 'rstrip()'.

 Also: 'lower()', 'upper()', 'capitalize()' and 'title()'.

Char
# Converts int to unicode char.
<str> = chr(<int>)
# Converts unicode char to int.
<int> = ord(<str>)
>>> ord('0'), ord('9')
(48, 57)
>>> ord('A'), ord('Z')
(65, 90)
ord('a'), ord('z')
(97, 122)
Initialize string literals in Python:
>>> s = "Python string"

>>> print(s)

Python string

>>> #using single quote and double quote

>>> s = "A Poor Woman's Journey."

>>> print(s)

A Poor Woman's Journey.


>>> s = "I read the article, 'A Poor Woman's Journey.'"

>>> print(s)

I read the article, 'A Poor Woman's Journey.'

>>> s = 'dir "c:\&temp\*.sas" /o:n /b > "c:\&temp\abc.txt"'

>>> print(s)

dir "c:\&temp\*.sas" /o:n /b > "c:\&tempbc.txt"

>>> #print multiple lines

>>> s = """jQuery exercises

JavaScript tutorial

Python tutorial and exercises ..."""

>>> print(s)

jQuery exercises

JavaScript tutorial

Python tutorial and exercises ...

>>> s = 'jQuery exercises\n JavaScript tutorial\n Python tutorial and exercises ...'

>>> print(s)

jQuery exercises

JavaScript tutorial

Python tutorial and exercises ...

>>>

Copy
Access character(s) from a string:

Characters in a string can be accessed using the standard [ ] syntax, and like
Java and C++, Python uses zero-based indexing, so if str is 'hello' str[2] is 'l'. If
the index is out of bounds for the string, Python raises an error.
>>> a = "Python string"

>>> print (a)

Python string
>>> b = a[2]

>>> print(b)

>>> a[0]

'P'

>>>

Copy
Explanation :

 The above statement selects character at position number 2 from a and assigns it to b.

 The expression in brackets is called an index that indicates which character we are
interested.

 The index is an offset from the beginning of the string, and the offset of the first letter is zero.

We can use any expression, including variables and operators, as an index


>>> a = "Python string"

>>> b = a[4+3]

>>> print(b)

>>>

Copy
The value of the index has to be an integer.
>>> a = "Python string"

>>> a[2.3]

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: string indices must be integers

>>>

Copy
Negative indices:

Alternatively, we can use negative indices, which count backward from the end of
the

Index -1 gives the last character.


>>> a = "Python string"

>>> a[-2]

'n'

>>> a[-8]

'n'

>>>

Copy
Python strings are immutable:

 Python strings are "immutable" which means they cannot be changed after they are created

 Therefore we can not use [ ] operator on the left side of an assignment.

 We can create a new string that is a variation of the original.


>>> a = "PYTHON"

>>> a[0] = "x"

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: 'str' object does not support item assignment

>>> a = "PYTHON"

# Concatenates a new first letter on to a slice of greeting.

>>> b = "X" + a[1:]

>>> print(b)

XYTHON

# It has no effect on the original string.

>>> print(a)
PYTHON

>>>

Copy
Python String concatenation:

The '+' operator is used to concatenate two strings.


>>> a = "Python" + "String"

>>> print(a)

PythonString

>>>

Copy
You can also use += to concatenate two strings.
>>> a = "Java"

>>> b = "Script"

>>> a+=b

>>> print(a)

JavaScript

>>>

Copy
Using '*' operator:
>>> a = "Python" + "String"

>>> b = "<" + a*3 + ">"

>>> print(b)

<PythonStringPythonStringPythonString>

>>>

Copy
String length:

len() is a built-in function which returns the number of characters in a string:


>>> a = "Python string"

>>> len(a)

13

>>> a[13]

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

IndexError: string index out of range

>>> a[12]

'g'

>>>

Copy
Traverse string with a while or for loop

 A lot of computations involve processing a string character by character at a time.

 They start at the beginning, select each character, in turn, do something to it, and continue
until the end.

 This pattern of processing is called a traversal.

 One can traverse string with a while or for loop:

Code:
a = "STRING"

i = 0

while i < len(a):

c = a[i]

print(c)

i = i + 1

Copy
Output:
>>>
S
T
R
I
N
G
>>>
Traversal with a for loop :

Print entire string on one line using for loop.

Code:
a = "Python"

i = 0

new=" "

for i in range (0,len(a)):

b=a[i]

# + used for concatenation

new = new+b

i = i + 1

# prints each char on one line

print(b)

print(new)

Copy
Output:
>>>
P
P
y
Py
t
Pyt
h
Pyth
o
Pytho
n
Python
>>>
String slices:

A segment of a string is called a slice. The "slice" syntax is used to get sub-parts
of a string. The slice s[start:end] is the elements beginning at the start (p) and
extending up to but not including end (q).

 The operator [p:q] returns the part of the string from the pth character to the qth character,
including the first but excluding the last.

 If we omit the first index (before the colon), the slice starts at the beginning of the string.

 If you omit the second index, the slice goes to the end of the string:

 If the first index is greater than or equal to the second the result is an empty string,
represented by two quotation marks.

Example-1
 
>> s = "Python"

Copy

 s[1:4] is 'yth' -- chars starting at index 1 and extending up to but not including index 4

 s[1:] is 'ython' -- omitting either index defaults to the start or end of the string

 s[:] is 'Python' -- Copy of the whole thing

 s[1:100] is 'ython' -- an index that is too big is truncated down to the string length

Python uses negative numbers to give easy access to the chars at the end of the
string. Negative index numbers count back from the end of the string:

 s[-1] is 'n' -- last char (1st from the end)


 s[-4] is 't' -- 4th from the end

 s[:-3] is 'pyt' -- going up to but not including the last 3 chars

 s[-3:] is 'hon' -- starting with the 3rd char from the end and extending to the end of the string.

Example-2
>>> a = "Python String"

>>> print (a[0:5])

Pytho

>>> print(a[6:11])

Stri

>>> print(a[5:13])

n String

>>>

Copy
>>> a = "Python String"

>>> print(a[:8])

Python S

>>> print(a[4:])

on String

>>> print(a[6:3])

>>>

Copy
Example-3
>>> a = "PYTHON"

>>> a[3]

'H'

>>> a[0:4]
'PYTH'

>>> a[3:5]

'HO'

>>> # The first two characters

...

>>> a[:2]

'PY'

>>> # All but the first three characters

...

>>> a[3:]

'HON'

>>>

Copy
Search a character in a string:

Code:
def search(char,str):

L=len(str)

print(L)

i = 0

while i < L:

if str[i]== char:

return 1

i = i + 1

return -1

print(search("P","PYTHON"))

Copy
Output:
>>>
6
1
>>>

 It takes a character and finds the index where that character appears in a string.

 If the character is not found, the function returns -1.

Another example
def search(char,str):

L=len(str)

print(L)

i = 0

while i < L:

if str[i]== char:

return 1

i = i + 1

return -1

print(search("S","PYTHON"))

Copy
Output:
>>>
6
-1
>>>

b'Python'

>>>

Python String Formatting


Last update on February 28 2020 12:12:57 (UTC/GMT +8 hours)

String Formatting
The format() method is used to perform a string formatting operation. The string
on which this method is called can contain literal text or replacement fields
delimited by braces {}. Each replacement field contains either the numeric index
of a positional argument or the name of a keyword argument.

Syntax:
str.format(*args, **kwargs)
Returns a copy of the string where each replacement field is replaced with the
string value of the corresponding argument.

Contents:

 Basic formatting

 Value conversion

 Padding and aligning strings

 Truncating long strings

 Combining truncating and padding

 Numbers

 Padding numbers

 Signed numbers

 Named placeholders

 Datetime

Basic formatting:

Example-1:
>>> '{} {}'.format('Python', 'Format')

'Python Format'
>>>

Copy
>>> '{} {}'.format(10, 30)

'10 30'

>>>

Copy
This following statement allows re-arrange the order of display without changing
the arguments.

Example-2:
>>> '{1} {0}'.format('Python', 'Format')

'Format Python'

>>>

Copy
Value conversion:

The new-style simple formatter calls by default the __format__() method of an


object for its representation. If you just want to render the output of str(...) or
repr(...) you can use the !s or !r conversion flags.

In %-style you usually use %s for the string representation but there is %r for a
repr(...) conversion.

Setup:
class Data(object):

def __str__(self):
return 'str'

def __repr__(self):
return 'repr'
Example-1:
class Data(object):
def __str__(self):

return 'str'

def __repr__(self):

return 'repr'

x='{0!s} {0!r}'.format(Data())

print (x)

Copy
Output:
str repr
In Python 3 there exists an additional conversion flag that uses the output of
repr(...) but uses ascii(...) instead.

Example-2:
class Data(object):

def __repr__(self):

return 'räpr'

x='{0!r} {0!a}'.format(Data())

print(x)

Copy
Output:
räpr r\xe4pr
Padding and aligning strings:

A value can be padded to a specific length. See the following examples where
the value '15' is encoded as part of the format string.

Note: The padding character can be spaces or a specified character.

Example:
Align right:
>>> '{:>15}'.format('Python')

' Python'

>>>

Copy
Align left:
>>> '{:15}'.format('Python')

'Python '

>>>

Copy
By argument:

In the previous example, the value '15' is encoded as part of the format string. It
is also possible to supply such values as an argument.

Example:
>>> '{:<{}s}'.format('Python', 15)

'Python '

>>>

Copy
In the following example we have used '*' as a padding character.

Example:
>>> '{:*<15}'.format('Python')

'Python*********'

>>>

Copy
Align center:

Example:
>>> '{:^16}'.format('Python')
' Python '

>>>

Copy
Truncating long strings:

In the following example, we have truncated ten characters from the left side of a
specified string.

Example:
>>> '{:.10}'.format('Python Tutorial')

'Python Tut'

>>>

Copy
By argument:

Example:
>>> '{:.{}}'.format('Python Tutorial', 10)

'Python Tut'

>>>

Copy
Combining truncating and padding

In the following example, we have combined truncating and padding.

Example:
>>> '{:10.10}'.format('Python')

'Python '

>>>

Copy
Numbers:

Integers:
>>> '{:d}'.format(24)
'24'

>>>

Copy
Floats:
>>> '{:f}'.format(5.12345678123)

'5.123457'

>>>

Copy
Padding numbers:

Similar to strings numbers.

Example-1:
>>> '{:5d}'.format(24)

' 24'

>>>

Copy
The padding value represents the length of the complete output for floating
points. In the following example '{:05.2f}' will display the float using five
characters with two digits after the decimal point.

Example-2:
>>> '{:05.2f}'.format(5.12345678123)

'05.12'

>>>

Copy
Signed numbers:

By default only negative numbers are prefixed with a sign, but you can display
numbers prefixed with the positive sign also.

Example-1:
>>> '{:+d}'.format(24)

'+24'

>>>

Copy
You can use a space character to indicate that negative numbers (should be
prefixed with a minus symbol) and a leading space should be used for positive
numbers.

Example-2:
>>> '{: d}'.format((- 24))

'-24'

>>>

Copy
Example-3:
>>> '{: d}'.format(24)

' 24'

>>>

Copy
You can control the position of the sign symbol relative to the padding.

Example-4:
>>> '{:=6d}'.format((- 24))

'- 24'

>>>

Copy
Named placeholders:

Both formatting styles support named placeholders. Here is an example:

Example-1:
>>> data = {'first': 'Place', 'last': 'Holder!'}
>>> '{first} {last}'.format(**data)

'Place Holder!'

>>>

Copy
.format() method can accept keyword arguments.

Example-2:
>>> '{first} {last}'.format(first='Place', last='Holder!')

'Place Holder!'

>>>

Copy
Datetime:

You can format and print datetime object as per your requirement.

Example:
>>> from datetime import datetime

>>> '{:%Y-%m-%d %H:%M}'.format(datetime(2016, 7, 26, 3, 57))

'2016-07-26 03:57'

>>>

Python: strftime()
Last update on February 28 2020 12:08:53 (UTC/GMT +8 hours)

strftime()
The strftime() function returns a string representing the date, controlled by an
explicit format string. Format codes referring to hours, minutes or seconds will
see 0 values.

Syntax:
date.strftime(format)
Complete list of formatting with examples:

{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2019-08-28 14:25:35.711200\n"
]
}
],
"source": [
"from datetime import datetime\n",
"now = datetime.now()\n",
"print(now)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %a : Weekday as locale’s abbreviated name.<br>\n",
"Example:<br>\n",
"Sun, Mon, …, Sat (en_US);<br>\n",
"So, Mo, …, Sa (de_DE)"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Weekday as locale’s abbreviated name: Wed\n"
]
}
],
"source": [
"day = now.strftime(\"%a\") \n",
"print(\"Weekday as locale’s abbreviated name:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %A : Weekday as locale’s full name<br>\n",
"Example:<br>\n",
"Sunday, Monday, …, Saturday (en_US);<br>\n",
"Sonntag, Montag, …, Samstag (de_DE)<br>"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Weekday as locale’s full name: Wednesday\n"
]
}
],
"source": [
"day = now.strftime(\"%A\") \n",
"print(\"Weekday as locale’s full name:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %w: Weekday as a decimal number, where 0 is Sunday and 6 is
Saturday.<br>\n",
"Example:<br>\n",
"0, 1, …, 6"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Weekday as a decimal number: 3\n"
]
}
],
"source": [
"day = now.strftime(\"%w\") \n",
"print(\"Weekday as a decimal number:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %d: Day of the month as a zero-padded decimal number.<br>\n",
"Example:<br>\n",
"01, 02, …, 31"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Day of the month as a zero-padded decimal number: 28\n"
]
}
],
"source": [
"day = now.strftime(\"%d\") \n",
"print(\"Day of the month as a zero-padded decimal number:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %b: Month as locale’s abbreviated name.<br>\n",
"Example:<br>\n",
"Jan, Feb, …, Dec (en_US);<br>\n",
"Jan, Feb, …, Dez (de_DE)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Month as locale's abbreviated name: Aug\n"
]
}
],
"source": [
"day = now.strftime(\"%b\") \n",
"print(\"Month as locale's abbreviated name:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %B: Month as locale’s full name.<br>\n",
"Example: <br>\n",
"January, February, …, December (en_US);<br>\n",
"Januar, Februar, …, Dezember (de_DE)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Month as locale's full Name: August\n"
]
}
],
"source": [
"day = now.strftime(\"%B\") \n",
"print(\"Month as locale's full Name:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %m: Month as a zero-padded decimal number.<br>\n",
"Example:<br>\n",
"01, 02, …, 12"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Month as a zero-padded decimal number: 08\n"
]
}
],
"source": [
"day = now.strftime(\"%m\") \n",
"print(\"Month as a zero-padded decimal number:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %y: Year without century as a zero-padded decimal number.<br>\n",
"Example:<br>\n",
"00, 01, …, 99"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Year without century as a zero-padded decimal number: 19\n"
]
}
],
"source": [
"day = now.strftime(\"%y\") \n",
"print(\"Year without century as a zero-padded decimal number:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %Y: Year with century as a decimal number.<br>\n",
"Example:<br>\n",
"0001, 0002, …, 2013, 2014, …, 9998, 9999"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Year with century as a decimal number: 2019\n"
]
}
],
"source": [
"day = now.strftime(\"%Y\") \n",
"print(\"Year with century as a decimal number:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %H: Hour (24-hour clock) as a zero-padded decimal number.<br>\n",
"Example:<br>\n",
"00, 01, …, 23"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hour as a zero-padded decimal number: 14\n"
]
}
],
"source": [
"day = now.strftime(\"%H\") \n",
"print(\"Hour as a zero-padded decimal number:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %I: Hour (12-hour clock) as a zero-padded decimal number.<br>\n",
"Example:<br>\n",
"01, 02, …, 12"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hour as a zero-paddes decimal number: 02\n"
]
}
],
"source": [
"day = now.strftime(\"%I\") \n",
"print(\"Hour as a zero-paddes decimal number:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %p: Locale’s equivalent of either AM or PM.<br>\n",
"Example:<br>\n",
"AM, PM (en_US);<br>\n",
"am, pm (de_DE)"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Locale's equivalent of either AM Or PM: PM\n"
]
}
],
"source": [
"day = now.strftime(\"%p\") \n",
"print(\"Locale's equivalent of either AM Or PM:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %M: Minute as a zero-padded decimal number.<br>\n",
"Example:<br>\n",
"00, 01, …, 59"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Minute as a zero-padded decimal number: 25\n"
]
}
],
"source": [
"day = now.strftime(\"%M\") \n",
"print(\"Minute as a zero-padded decimal number:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %S: Second as a zero-padded decimal number.<br>\n",
"Example:<br>\n",
"00, 01, …, 59"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Second as a zero-padded decimal number: 35\n"
]
}
],
"source": [
"day = now.strftime(\"%S\") \n",
"print(\"Second as a zero-padded decimal number:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %f: Microsecond as a decimal number, zero-padded on the
left.<br>\n",
"Example:<br>\n",
"000000, 000001, …, 999999"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Microsecond as a decimal number, zero-padded on the left: 711200\n"
]
}
],
"source": [
"day = now.strftime(\"%f\") \n",
"print(\"Microsecond as a decimal number, zero-padded on the left:\",
day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %z: UTC offset in the form ±HHMM[SS[.ffffff]] (empty string if
the object is naive).<br>\n",
"Example:<br>\n",
"(empty), +0000, -0400, +1030, +063415, -030712.345216"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"UTC offset in the form ±HHMM[SS[.ffffff]]: +0100\n"
]
}
],
"source": [
"import time\n",
"from datetime import time, tzinfo, timedelta\n",
"class TZ1(tzinfo):\n",
" def utcoffset(self, dt):\n",
" return timedelta(hours=1)\n",
" def dst(self, dt):\n",
" return timedelta(0)\n",
" def tzname(self,dt):\n",
" return \"+01:00\"\n",
" def __repr__(self):\n",
" return f\"{self.__class__.__name__}()\"\n",
"t = time(10, 8, 55, tzinfo=TZ1())\n",
"day = t.strftime(\"%z\") \n",
"print(\"UTC offset in the form ±HHMM[SS[.ffffff]]:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %Z: Time zone name (empty string if the object is naive).<br>\n",
"Example:<br>\n",
"(empty), UTC, EST, CST"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Time zone name: +01:00\n"
]
}
],
"source": [
"import time\n",
"from datetime import time, tzinfo, timedelta\n",
"class TZ1(tzinfo):\n",
" def utcoffset(self, dt):\n",
" return timedelta(hours=1)\n",
" def dst(self, dt):\n",
" return timedelta(0)\n",
" def tzname(self,dt):\n",
" return \"+01:00\"\n",
" def __repr__(self):\n",
" return f\"{self.__class__.__name__}()\"\n",
"t = time(10, 8, 55, tzinfo=TZ1())\n",
"day = t.strftime(\"%Z\")\n",
"print(\"Time zone name:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %j: Day of the year as a zero-padded decimal number.<br>\n",
"Example:<br>\n",
"001, 002, …, 366"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Day of the year as a zero-padded decimal number: 240\n"
]
}
],
"source": [
"day = now.strftime(\"%j\") \n",
"print(\"Day of the year as a zero-padded decimal number:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %U: Week number of the year (Sunday as the first day of the week)
as a zero padded decimal number.<br> All days in a new year preceding the
first Sunday are considered to be in week 0.<br>\n",
"Example:<br>\n",
"00, 01, …, 53"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Week number of the year as a zero-padded decimal number: 34\n"
]
}
],
"source": [
"day = now.strftime(\"%U\") \n",
"print(\"Week number of the year as a zero-padded decimal number:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %W: Week number of the year (Monday as the first day of the week)
as a decimal number.<br> All days in a new year preceding the first Monday are
considered to be in week 0.<br>\n",
"Example:<br>\n",
"00, 01, …, 53 "
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Week number of the year as a zero-padded decimal number: 34\n"
]
}
],
"source": [
"day = now.strftime(\"%W\") \n",
"print(\"Week number of the year as a zero-padded decimal number:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %c: Locale’s appropriate date and time representation.<br>\n",
"Example:<br>\n",
"Tue Aug 16 21:30:00 1988 (en_US);<br>\n",
"Di 16 Aug 21:30:00 1988 (de_DE)"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Locale's appropriate date and time representation: Wed Aug 28 14:25:35
2019\n"
]
}
],
"source": [
"day = now.strftime(\"%c\") \n",
"print(\"Locale's appropriate date and time representation:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %x: Locale’s appropriate date representation.<br>\n",
"Example:<br>\n",
"08/16/88 (None);<br>\n",
"08/16/1988 (en_US);<br>\n",
"16.08.1988 (de_DE)"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Locale's appropriate date representation: 08/28/19\n"
]
}
],
"source": [
"day = now.strftime(\"%x\") \n",
"print(\"Locale's appropriate date representation:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %X: Locale’s appropriate time representation.<br>\n",
"Example:<br>\n",
"21:30:00 (en_US);<br>\n",
"21:30:00 (de_DE)"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Locale's appropriate time representation: 14:25:35\n"
]
}
],
"source": [
"day = now.strftime(\"%X\") \n",
"print(\"Locale's appropriate time representation:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %%: A literal '%' character.<br>\n",
"Example:<br>\n",
"%"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"A literal '%' character: %\n"
]
}
],
"source": [
"day = now.strftime(\"%%\") \n",
"print(\"A literal '%' character:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Several additional directives not required by the C89 standard are
included for convenience.<br> These parameters all correspond to ISO 8601 date
values. These may not be available on all platforms when used with the
strftime() method.<br> The ISO 8601 year and ISO 8601 week directives are not
interchangeable with the year and week number directives above.<br> Calling
strptime() with incomplete or ambiguous ISO 8601 directives will raise a
ValueError."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %G: ISO 8601 year with century representing the year that contains
the greater part of the ISO week (%V).<br>\n",
"Example:<br>\n",
"0001, 0002, …, 2013, 2014, …, 9998, 9999"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"ISO 8601 year with century representing the year that contains the
greater part of the ISO week: 2019\n"
]
}
],
"source": [
"day = now.strftime(\"%G\") \n",
"print(\"ISO 8601 year with century representing the year that contains
the greater part of the ISO week:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %u: ISO 8601 weekday as a decimal number where 1 is
Monday.<br>\n",
"Example:<br>\n",
"1, 2, …, 7"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"ISO 8601 weekday as a decimal number where 1 is Monday: 3\n"
]
}
],
"source": [
"from datetime import datetime\n",
"now = datetime.now()\n",
"day = now.strftime(\"%u\") \n",
"print(\"ISO 8601 weekday as a decimal number where 1 is Monday:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Code - %V: ISO 8601 week as a decimal number with Monday as the first day
of the week. Week 01 is the week containing Jan 4.<br>\n",
"Example:<br>\n",
"01, 02, …, 53"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"ISO 8601 week as a decimal number with Monday as the first day of the
week.: 35\n"
]
}
],
"source": [
"day = now.strftime(\"%V\") \n",
"print(\"ISO 8601 week as a decimal number with Monday as the first day of
the week.:\", day)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"New in version 3.6: %G, %u and %V were added."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.1"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Python List
Last update on February 28 2020 12:07:32 (UTC/GMT +8 hours)

List
A list is a container which holds comma-separated values (items or elements)
between square brackets where items or elements need not all have the same
type.

In general, we can define a list as an object that contains multiple data items
(elements). The contents of a list can be changed during program execution. The
size of a list can also change during execution, as elements are added or
removed from it.

Note: There are much programming languages which allow us to create arrays,
which are objects similar to lists. Lists serve the same purpose as arrays and
have many more built-in capabilities. Traditional arrays can not be created in
Python.

Examples of lists:

 numbers = [10, 20, 30, 40, 50]


 names = ["Sara", "David", "Warner", "Sandy"]

 student_info = ["Sara", 1, "Chemistry"]

Contents:

 List commands

 Create a Python list

 List indices

 Add an item to the end of the list

 Insert an item at a given position

 Modify an element by using the index of the element

 Remove an item from the list

 Remove all items from the list

 Slice Elements from a List

 Remove the item at the given position in the list, and return it

 Return the index in the list of the first item whose value is x

 Return the number of times 'x' appear in the list

 Sort the items of the list in place

 Reverse the elements of the list in place

 Return a shallow copy of the list

 Search the Lists and find elements

 Lists are mutable

 Convert a list to a tuple in python

 How to use the double colon [ : : ]?

 Find largest and the smallest items in a list

 Compare two lists in Python?

 Nested lists in Python


 How can I get the index of an element contained in the list?

 Using Lists as Stacks

 Using Lists as Queues

 Python Code Editor

 Python List Exercises

Lists: Commands
<list> = <list>[from_inclusive : to_exclusive : ±step_size]

<list>.append(<el>)
# Or: <list> += [<el>]
<list>.extend(<collection>)
# Or: <list> += <collection>

<list>.sort()
<list>.reverse()
<list> = sorted(<collection>)
<iter> = reversed(<list>)

sum_of_elements = sum(<collection>)
elementwise_sum = [sum(pair) for pair in zip(list_a, list_b)]
sorted_by_second = sorted(<collection>, key=lambda el: el[1])
sorted_by_both = sorted(<collection>, key=lambda el: (el[1],
el[0]))
flatter_list = list(itertools.chain.from_iterable(<list>))
product_of_elems = functools.reduce(lambda out, x: out * x,
<collection>)
list_of_chars = list(<str>)

# Returns number of occurrences. Also works on strings.


<int> = <list>.count(<el>)
# Returns index of first occurrence or raises ValueError.
index = <list>.index(<el>)
# Inserts item at index and moves the rest to the right.
<list>.insert(index, <el>)
# Removes and returns item at index or from the end.
<el> = <list>.pop([index])
# Removes first occurrence of item or raises ValueError.
<list>.remove(<el>)
# Removes all items. Also works on dictionary and set.
<list>.clear()
Create a Python list
Following list contains all integer values:
>>> my_list1 = [5, 12, 13, 14] # the list contains all integer values

>>> print(my_list1)

[5, 12, 13, 14]

>>>

Copy
Following list contains all string:
>>> my_list2 = ['red', 'blue', 'black', 'white'] # the list contains all string

values

>>> print(my_list2)

['red', 'blue', 'black', 'white']

>>>

Copy
Following list contains a string, an integer and a float values:
>>> my_list3 = ['red', 12, 112.12] # the list contains a string, an integer and

a float values

>>> print(my_list3)

['red', 12, 112.12]

>>>

Copy
A list without any element is called an empty list. See the following statements.
>>> my_list=[]

>>> print(my_list)

[]

>>>
Copy
Use + operator to create a new list that is a concatenation of two lists and use *
operator to repeat a list. See the following statements.
>>> color_list1 = ["White", "Yellow"]

>>> color_list2 = ["Red", "Blue"]

>>> color_list3 = ["Green", "Black"]

>>> color_list = color_list1 + color_list2 + color_list3

>>> print(color_list)

['White', 'Yellow', 'Red', 'Blue', 'Green', 'Black']

>>> number = [1,2,3]

>>> print(number[0]*4)

>>> print(number*4)

[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]

>>>

Copy

List indices
List indices work the same way as string indices, list indices start at 0. If an index
has a positive value it counts from the beginning and similarly it counts backward
if the index has a negative value. As positive integers are used to index from the
left end and negative integers are used to index from the right end, so every item
of a list gives two alternatives indices. Let create a list called color_list with four
items.
color_list=["RED", "Blue", "Green", "Black"]

Item RED Blue Gr

Index (from left)  0  1  2


Index (from right) -4 -3 -2

If you give any index value which is out of range then interpreter creates an error
message. See the following statements.
>>> color_list=["Red", "Blue", "Green", "Black"] # The list have four elements

indices start at 0 and end at 3

>>> color_list[0] # Return the First Element

'Red'

>>> print(color_list[0],color_list[3]) # Print First and Last Elements

Red Black

>>> color_list[-1] # Return Last Element

'Black'

>>> print(color_list[4]) # Creates Error as the indices is out of range

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

IndexError: list index out of range

>>>

Copy

Add an item to the end of the list


See the following statements:
>>> color_list=["Red", "Blue", "Green", "Black"]

>>> print(color_list)

['Red', 'Blue', 'Green', 'Black']

>>> color_list.append("Yellow")

>>> print(color_list)

['Red', 'Blue', 'Green', 'Black', 'Yellow']

>>>

Copy

Insert an item at a given position


See the following statements:
>>> color_list=["Red", "Blue", "Green", "Black"]

>>> print(color_list)

['Red', 'Blue', 'Green', 'Black']

>>> color_list.insert(2, "White") #Insert an item at third position

>>> print(color_list)

['Red', 'Blue', 'White', 'Green', 'Black']

>>>

Copy

Modify an element by using the index of the element


See the following statements:
>>> color_list=["Red", "Blue", "Green", "Black"]

>>> print(color_list)

['Red', 'Blue', 'Green', 'Black']

>>> color_list[2]="Yellow" #Change the third color

>>> print(color_list)

['Red', 'Blue', 'Yellow', 'Black']

>>>

Copy

Remove an item from the list


See the following statements:
>>> color_list=["Red", "Blue", "Green", "Black"]

>>> print(color_list)

['Red', 'Blue', 'Green', 'Black']

>>> color_list.remove("Black")

>>> print(color_list)

['Red', 'Blue', 'Green']

Copy

Remove all items from the list


See the following statements:
>>> color_list=["Red", "Blue", "Green", "Black"]

>>> print(color_list)

['Red', 'Blue', 'Green', 'Black']

>>> color_list.clear()

>>> print(color_list)

[]

>>>

Copy

List Slices
Lists can be sliced like strings and other sequences.

Syntax:
sliced_list = List_Name[startIndex:endIndex]
This refers to the items of a list starting at index startIndex and stopping just
before index endIndex. The default values for list are 0 (startIndex) and the end
(endIndex) of the list. If you omit both indices, the slice makes a copy of the
original list.

Cut first two items from a list:

See the following statements:


>>> color_list=["Red", "Blue", "Green", "Black"] # The list have four elements

indices start at 0 and end at 3

>>> print(color_list[0:2]) # cut first two items

['Red', 'Blue']

>>>

Copy
Cut second item from a list:
See the following statements:
>>> color_list=["Red", "Blue", "Green", "Black"] # The list have four elements

indices start at 0 and end at 3

>>> print(color_list[1:2])

['Blue']

>>> print(color_list[1:-2])

['Blue']

>>>

Copy
Cut second and third elements from a list:
See the following statements:
>>> color_list=["Red", "Blue", "Green", "Black"] # The list have four elements

indices start at 0 and end at 3

>>> print(color_list[1:-1])

['Blue', 'Green']

>>>

Copy
Cut first three items from a list:
See the following statements:
>>> color_list=["Red", "Blue", "Green", "Black"] # The list have four elements

indices start at 0 and end at 3

>>> print(color_list[:3]) # cut first three items

['Red', 'Blue', 'Green']

>>>

Copy
Creates copy of original list:
See the following statements:
>>> color_list=["Red", "Blue", "Green", "Black"] # The list have four elements

indices start at 0 and end at 3

>>> print(color_list[:]) # Creates copy of original list

['Red', 'Blue', 'Green', 'Black']

>>>

Copy

Remove the item at the given position in the list, and return

it
See the following statements:
>>> color_list=["Red", "Blue", "Green", "Black"]

>>> print(color_list)

['Red', 'Blue', 'Green', 'Black']

>>> color_list.pop(2) # Remove second item and return it

'Green'

>>> print(color_list)

['Red', 'Blue', 'Black']

>>>

Copy

Return the index in the list of the first item whose value is

x
See the following statements:
>>> color_list=["Red", "Blue", "Green", "Black"]

>>> print(color_list)

['Red', 'Blue', 'Green', 'Black']

>>> color_list.index("Red")

>>> color_list.index("Black")

>>>

Copy

Return the number of times 'x' appear in the list


See the following statements:
>>> color_list=["Red", "Blue", "Green", "Black"]

>>> print(color_list)

['Red', 'Blue', 'Green', 'Black']

>>> color_list=["Red", "Blue", "Green", "Black", "Blue"]

>>> print(color_list)

['Red', 'Blue', 'Green', 'Black', 'Blue']

>>> color_list.count("Blue")

>>>

Copy

Sort the items of the list in place


See the following statements:
>>> color_list=["Red", "Blue", "Green", "Black"]

>>> print(color_list)

['Red', 'Blue', 'Green', 'Black']

>>> color_list.sort(key=None, reverse=False)

>>> print(color_list)

['Black', 'Blue', 'Green', 'Red']

>>>

Copy

Reverse the elements of the list in place


>>> color_list=["Red", "Blue", "Green", "Black"]

>>> print(color_list)

['Red', 'Blue', 'Green', 'Black']


>>> color_list.reverse()

>>> print(color_list)

['Black', 'Green', 'Blue', 'Red']

>>>

Copy

Return a shallow copy of the list


>>> color_list=["Red", "Blue", "Green", "Black"]

>>> print(color_list)

['Red', 'Blue', 'Green', 'Black']

>>> color_list.copy()

['Red', 'Blue', 'Green', 'Black']

>>>

Copy

Search the Lists and find Elements


>>> color_list=["Red", "Blue", "Green", "Black"]

>>> print(color_list)

['Red', 'Blue', 'Green', 'Black']

>>> color_list.index("Green")

>>>

Copy

Lists are Mutable


Items in the list are mutable i.e. after creating a list you can change any item in
the list. See the following statements.
>>> color_list=["Red", "Blue", "Green", "Black"]

>>> print(color_list[0])

Red

>>> color_list[0]="White" # Change the value of first item "Red" to "White"

>>> print(color_list)

['White', 'Blue', 'Green', 'Black']

>>> print(color_list[0])

White

>>>

Copy

Convert a list to a tuple in Python


>>> listx = [1, 2, 3, 4]

>>> print(listx)

[1, 2, 3, 4]

>>> tuplex = tuple(listx)

>>> print(tuplex)

(1, 2, 3, 4)

>>>

Copy

How to use the double colon [ : : ]?


>>> listx=[1, 5, 7, 3, 2, 4, 6]

>>> print(listx)
[1, 5, 7, 3, 2, 4, 6]

>>> sublist=listx[2:7:2] #list[start:stop:step], #step specify an increment

between the elements to cut of the list.

>>> print(sublist)

[7, 2, 6]

>>> sublist=listx[::3] #returns a list with a jump every 2 times.

>>> print(sublist)

[1, 3, 6]

>>> sublist=listx[6:2:-2] #when step is negative the jump is made back

>>> print(sublist)

[6, 2]

>>>

Copy

Find the largest and the smallest item in a list


>>> listx=[5, 10, 3, 25, 7, 4, 15]

>>> print(listx)

[5, 10, 3, 25, 7, 4, 15]

>>> print(max(listx)) # the max() function of built-in allows to know the highest

value in the list.

25

>>> print(min(listx)) #the min() function of built-in allows to know the lowest

value in the list.

>>>

Copy
Compare two lists in Python
>>> listx1, listx2=[3, 5, 7, 9], [3, 5, 7, 9]

>>> print (listx1 == listx2)

True

>>> listx1, listx2=[9, 7, 5, 3], [3, 5, 7, 9] #create two lists equal, but
unsorted.

>>> print(listx1 == listx2)

False

>>> listx1, listx2 =[2, 3, 5, 7], [3, 5, 7, 9] #create two different list

>>> print(listx1 == listx2)

False

>>> print(listx1.sort() == listx2.sort()) #order and compare

True

>>>

Copy

Nested lists in Python


>>> listx = [["Hello", "World"], [0, 1, 2, 3, 4, 5]]

>>> print(listx)

[['Hello', 'World'], [0, 1, 2, 3, 4, 5]]

>>> listx = [["Hello", "World"], [0, 1, 2, 3, 3, 5]]

>>> print(listx)

[['Hello', 'World'], [0, 1, 2, 3, 3, 5]]

>>> print(listx[0][1]) #The first [] indicates the index of the outer


list.

World

>>> print(listx[1][3]) #the second [] indicates the index nested lists.


3

>>> listx.append([True, False]) #add new items

>>> print(listx)

[['Hello', 'World'], [0, 1, 2, 3, 3, 5], [True, False]]

>>> listx[1][2]=4

>>> print(listx)

[['Hello', 'World'], [0, 1, 4, 3, 3, 5], [True, False]] #update value


items

>>>

Copy

How can I get the index of an element contained in the

list?
>>> listy = list("HELLO WORLD")

>>> print(listy)

['H', 'E', 'L', 'L', 'O', ' ', 'W', 'O', 'R', 'L', 'D']

>>> index = listy.index("L") #get index of the first item whose value is passed
as parameter

>>> print(index)

>>> index = listy.index("L", 4) #define the index from which you want to search

>>> print(index)

>>> index = listy.index("O", 3, 5) #define the segment of the list to be


searched

>>> print(index)

>>>
Copy

Using Lists as Stacks


>>> color_list=["Red", "Blue", "Green", "Black"]

>>> print(color_list)

['Red', 'Blue', 'Green', 'Black']

>>> color_list.append("White")

>>> color_list.append("Yellow")

>>> print(color_list)

['Red', 'Blue', 'Green', 'Black', 'White', 'Yellow']

>>> color_list.pop()

'Yellow'

>>> color_list.pop()

'White'

>>> color_list.pop()

'Black'

>>> color_list

['Red', 'Blue', 'Green']

>>>

Copy

Using Lists as Queues


>>> from collections import deque

>>> color_list = deque(["Red", "Blue", "Green", "Black"])

>>> color_list.append("White") # White arrive

>>> print(color_list)
deque(['Red', 'Blue', 'Green', 'Black', 'White'])

>>> color_list.append("Yellow") # Yellow arrive

>>> print(color_list)

deque(['Red', 'Blue', 'Green', 'Black', 'White', 'Yellow'])

>>> color_list.popleft() # The first to arrive now leaves

'Red'

>>> print(color_list)

deque(['Blue', 'Green', 'Black', 'White', 'Yellow'])

>>> color_list.popleft() # The second to arrive now leaves

'Blue'

>>> print(color_list)

deque(['Green', 'Black', 'White', 'Yellow'])

>>> print(color_list) # Remaining queue in order of arrival

deque(['Green', 'Black', 'White', 'Yellow'])

>>>

Python Dictionary
Last update on February 28 2020 12:07:03 (UTC/GMT +8 hours)

Dictionary
Python dictionary is a container of the unordered set of objects like lists. The
objects are surrounded by curly braces { }. The items in a dictionary are a
comma-separated list of key:value pairs where keys and values are Python data
type.

Each object or value accessed by key and keys are unique in the dictionary. As
keys are used for indexing, they must be the immutable type (string, number, or
tuple). You can create an empty dictionary using empty curly braces.
 

Contents :

 Dictionary commands

 Create a new dictionary in Python

 Get value by key in Python dictionary

 Add key/value to a dictionary in Python

 Iterate over Python dictionaries using for loops

 Remove a key from a Python dictionary

 Sort a Python dictionary by key


 Find the maximum and minimum value of a Python dictionary

 Concatenate two Python dictionaries into a new one

 Test whether a Python dictionary contains a specific key

 Find the length of a Python dictionary

 Python Dictionary - Exercises, Practice, Solution

Dictionary: Commands
# Coll. of keys that reflects changes.
<view> = <dict>.keys()
# Coll. of values that reflects changes.
<view> = <dict>.values()
# Coll. of key-value tuples.
<view> = <dict>.items()

# Returns default if key is missing.


value = <dict>.get(key, default=None)
# Returns and writes default if key is missing.
value = <dict>.setdefault(key, default=None)
# Creates a dict with default value of type.
<dict> = collections.defaultdict(<type>)
# Creates a dict with default value 1.
<dict> = collections.defaultdict(lambda: 1)

<dict>.update(<dict>)
# Creates a dict from coll. of key-value pairs.
<dict> = dict(<collection>)
# Creates a dict from two collections.
<dict> = dict(zip(keys, values))
# Creates a dict from collection of keys.
<dict> = dict.fromkeys(keys [, value])

# Removes item or raises KeyError.


value = <dict>.pop(key)
# Filters dictionary by keys.
{k: v for k, v in <dict>.items() if k in keys}

Counter

>>> from collections import Counter


>>> colors = ['blue', 'red', 'blue', 'red', 'blue']
>>> counter = Counter(colors)
>>> counter['yellow'] += 1
Counter({'blue': 3, 'red': 2, 'yellow': 1})
>>> counter.most_common()[0]
('blue', 3)
Create a new dictionary in Python
>>> #Empty dictionary

>>> new_dict = dict()

>>> new_dict = {}

>>> print(new_dict)

{}

>>> #Dictionary with key-vlaue

>>> color = {"col1" : "Red", "col2" : "Green", "col3" : "Orange" }

>>> color

{'col2': 'Green', 'col3': 'Orange', 'col1': 'Red'}

>>>

Copy
Get value by key in Python dictionary
>>> #Declaring a dictionary

>>> dict = {1:20.5, 2:3.03, 3:23.22, 4:33.12}

>>> #Access value using key

>>> dict[1]

20.5

>>> dict[3]

23.22

>>> #Accessing value using get() method

>>> dict.get(1)

20.5

>>> dict.get(3)

23.22
>>>

Copy
Add key/value to a dictionary in Python
>>> #Declaring a dictionary with a single element

>>> dic = {'pdy1':'DICTIONARY'}

>>>print(dic)

{'pdy1': 'DICTIONARY'}

>>> dic['pdy2'] = 'STRING'

>>> print(dic)

{'pdy1': 'DICTIONARY', 'pdy2': 'STRING'}

>>>

>>> #Using update() method to add key-values pairs in to dictionary

>>> d = {0:10, 1:20}

>>> print(d)

{0: 10, 1: 20}

>>> d.update({2:30})

>>> print(d)

{0: 10, 1: 20, 2: 30}

>>>

Copy
Iterate over Python dictionaries using for loops

Code:
d = {'Red': 1, 'Green': 2, 'Blue': 3}

for color_key, value in d.items():

print(color_key, 'corresponds to ', d[color_key])

Copy
Output:
>>>
Green corresponds to 2
Red corresponds to 1
Blue corresponds to 3
>>>
Remove a key from a Python dictionary

Code:
myDict = {'a':1,'b':2,'c':3,'d':4}

print(myDict)

if 'a' in myDict:

del myDict['a']

print(myDict)

Copy
Output:
>>>
{'d': 4, 'a': 1, 'b': 2, 'c': 3}
{'d': 4, 'b': 2, 'c': 3}
>>>
Sort a Python dictionary by key

Code:
color_dict = {'red':'#FF0000',

'green':'#008000',

'black':'#000000',

'white':'#FFFFFF'}

for key in sorted(color_dict):

print("%s: %s" % (key, color_dict[key]))

Copy
Output:
>>>
black: #000000
green: #008000
red: #FF0000
white: #FFFFFF
>>>
Find the maximum and minimum value of a Python dictionary

Code:
my_dict = {'x':500, 'y':5874, 'z': 560}

key_max = max(my_dict.keys(), key=(lambda k: my_dict[k]))

key_min = min(my_dict.keys(), key=(lambda k: my_dict[k]))

print('Maximum Value: ',my_dict[key_max])

print('Minimum Value: ',my_dict[key_min])

Copy
Output:
>>>
Maximum Value: 5874
Minimum Value: 500
>>>
Concatenate two Python dictionaries into a new one

Code:
dic1={1:10, 2:20}

dic2={3:30, 4:40}

dic3={5:50,6:60}

dic4 = {}

for d in (dic1, dic2, dic3): dic4.update(d)

print(dic4)

Copy
Output:
>>>
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
>>>
Test whether a Python dictionary contains a specific key

Code:
fruits = {}

fruits["apple"] = 1

fruits["mango"] = 2

fruits["banana"] = 4

# Use in.

if "mango" in fruits:

print("Has mango")

else:

print("No mango")

# Use in on nonexistent key.

if "orange" in fruits:

print("Has orange")

else:

print("No orange")

Copy
Output
>>>
Has mango
No orange
>>>
Find the length of a Python dictionary

Code:
fruits = {"mango": 2, "orange": 6}
# Use len() function to get the length of the dictionary

print("Length:", len(fruits))

Copy
Output:
>>>
Length: 2
>>>

Python Tuples
Last update on February 28 2020 12:16:21 (UTC/GMT +8 hours)

Tuples
A tuple is a container which holds a series of comma-separated values (items or
elements) between parentheses such as an (x, y) co-ordinate. Tuples are like
lists, except they are immutable (i.e. you cannot change its content once created)
and can hold mix data types. Tuples play a sort of "struct" role in Python -- a
convenient way to pass around a little logical, fixed size bundle of values.

Contents:

 Tuple commands

 Create a tuple

 How to get an item of the tuple in Python?

 How to know if an element exists within a tuple in Python?

 List to tuple

 Unpack a tuple in several variables

 Add item in Python tuple!

 Clone a tuple
 In Python how to know the number of times an item has repeated

 Remove an item from a tuple

 Slice a tuple

 How to get the index of an item of the tuple in Python?

 The size of a tuple

 How operators + and * are used with a Python tuple?

 Slice of a tuple using step parameter.

 Modify items of a tuple

 Python Data Types: Tuple - Exercises, Practice, Solution

Tuple: Commands

Tuple is an immutable and hashable list.


<tuple> = ()
<tuple> = (<el>, )
<tuple> = (<el_1>, <el_2> [, ...])
Named Tuple

Tuple's subclass with named elements.


>>> from collections import namedtuple
>>> Point = namedtuple('Point', 'x y')
>>> p = Point(1, y=2)
Point(x=1, y=2)
>>> p[0]
1
>>> p.x
1
>>> getattr(p, 'y')
2
>>> p._fields # Or: Point._fields
('x', 'y')
Create a tuple?

To create a tuple, just list the values within parenthesis separated by commas.
The "empty" tuple is just an empty pair of parenthesis
>>> #create an empty tuple
>>> tuplex = ()

>>> print (tuplex)

()

>>> #create a tuple with different data types

>>> tuplex = ('tuple', False, 3.2, 1)

>>> print (tuplex)

('tuple', False, 3.2, 1)

>>> #create a tuple with numbers, notation without parenthesis

>>> tuplex = 4, 7, 3, 8, 1

>>> print (tuplex)

(4, 7, 3, 8, 1)

>>> #create a tuple of one item, notation without parenthesis

>>> tuplex = 4,

>>> print (tuplex)

(4,)

>>> #create an empty tuple with tuple() function built-in Python

>>> tuplex = tuple()

>>> print (tuplex)

()

>>> #create a tuple from a iterable object

>>> tuplex = tuple([True, False])

>>> print (tuplex)

(True, False)

>>>

Copy
How to get an item of the tuple in Python?
>>> #create a tuple

>>> tuplex = ("w", 3, "r", "e", "s", "o", "u", "r", "c", "e")
>>> print(tuplex)

('w', 3, 'r', 'e', 's', 'o', 'u', 'r', 'c', 'e')

>>> #get item (4th element)of the tuple by index

>>> item = tuplex[3]

>>> print(item)

>>> #get item (4th element from last)by index negative

>>> item1 = tuplex[-4]

>>> print(item1)

>>>

Copy
How to know if an element exists within a tuple in Python?
>>> #create a tuple

>>> tuplex = ("w", 3, "r", "e", "s", "o", "u", "r", "c", "e")

>>> print(tuplex)

('w', 3, 'r', 'e', 's', 'o', 'u', 'r', 'c', 'e')

>>> #use in statement

>>> print("r" in tuplex)

True

>>> print(5 in tuplex)

False

>>>

Copy
List to tuple
>>> #create list

>>> listx = [5, 10, 7, 4, 15, 3]

>>> print(listx)
[5, 10, 7, 4, 15, 3]

>>> #use the tuple() function built-in Python, passing as parameter the list

>>> tuplex = tuple(listx)

>>> print(tuplex)

(5, 10, 7, 4, 15, 3)

>>>

Copy
Unpack a tuple in several variables
>>> #create a tuple

>>> tuplex = 4, 8, 3

>>> print(tuplex)

(4, 8, 3)

>>> n1, n2, n3 = tuplex

>>> #unpack a tuple in variables

>>> print(n1 + n2 + n3)

15

>>> #the number of variables must be equal to the number of items of the tuple

>>> n1, n2, n3, n4 = tuplex

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

ValueError: need more than 3 values to unpack

>>>

Copy
Add item in Python tuple!
>>> #create a tuple

>>> tuplex = (4, 6, 2, 8, 3, 1)

>>> print(tuplex)

(4, 6, 2, 8, 3, 1)
>>> #tuples are immutable, so you can not add new elements

>>> #using merge of tuples with the + operator you can add an element and it will
create a new tuple

>>> tuplex = tuplex + (9,)

>>> print(tuplex)

(4, 6, 2, 8, 3, 1, 9)

>>> #adding items in a specific index

>>> tuplex = tuplex[:5] + (15, 20, 25) + tuplex[:5]

>>> print(tuplex)

(4, 6, 2, 8, 3, 15, 20, 25, 4, 6, 2, 8, 3)

>>> #converting the tuple to list

>>> listx = list(tuplex)

>>> #use different ways to add items in list

>>> listx.append(30)

>>> tuplex = tuple(listx)

>>> print(tuplex)

(4, 6, 2, 8, 3, 15, 20, 25, 4, 6, 2, 8, 3, 30)

>>>

Copy
Clone a tuple
>>> from copy import deepcopy

>>> #create a tuple

>>> tuplex = ("HELLO", 5, [], True)

>>> print(tuplex)

('HELLO', 5, [], True)

>>> #make a copy of a tuple using deepcopy() function

>>> tuplex_clone = deepcopy(tuplex)

>>> tuplex_clone[2].append(50)
>>> print(tuplex_clone)

('HELLO', 5, [50], True)

>>> print(tuplex)

('HELLO', 5, [], True)

>>>

Copy
In Python how to know the number of times an item has repeated
>>> #create a tuple

>>> tuplex = 2, 4, 5, 6, 2, 3, 4, 4, 7

>>> print(tuplex)

(2, 4, 5, 6, 2, 3, 4, 4, 7)

>>> #return the number of times it appears in the tuple.

>>> count = tuplex.count(4)

>>> print(count)

>>> count = tuplex.count(7)

>>> print(count)

>>> count = tuplex.count(5)

>>> print (count)

>>>

Copy
Remove an item from a tuple
>>> #create a tuple

>>> tuplex = "w", 3, "d", "r", "e", "s", "l"

>>> print(tuplex)
('w', 3, 'd', 'r', 'e', 's', 'l')

>>> #tuples are immutable, so you can not remove elements

>>> #using merge of tuples with the + operator you can remove an item and it will
create a new tuple

>>> tuplex = tuplex[:2] + tuplex[3:]

>>> print(tuplex)

('w', 3, 'r', 'e', 's', 'l')

>>> #converting the tuple to list

>>> listx = list(tuplex)

>>> #use different ways to remove an item of the list

>>> listx.remove("l")

>>> #converting the tuple to list

>>> tuplex = tuple(listx)

>>> print(tuplex)

('w', 3, 'r', 'e', 's')

>>>

Copy
Slice a tuple
>>> #create a tuple

>>> tuplex = (2, 4, 3, 5, 4, 6, 7, 8, 6, 1)

>>> #used tuple[start:stop] the start index is inclusive and the stop index

>>> _slice = tuplex[3:5]

#is exclusive.

>>> print(_slice)

(5, 4)

>>> #if the start index isn't defined, is taken from the beg inning of the tuple.

>>> _slice = tuplex[:6]

>>> print(_slice)
(2, 4, 3, 5, 4, 6)

>>> #if the end index isn't defined, is taken until the end of the tuple

>>> _slice = tuplex[5:]

>>> print(_slice)

(6, 7, 8, 6, 1)

>>> #if neither is defined, returns the full tuple

>>> _slice = tuplex[:]

>>> print(_slice)

(2, 4, 3, 5, 4, 6, 7, 8, 6, 1)

>>> #The indexes can be defined with negative values

>>> _slice = tuplex[-8:-4]

>>> print(_slice)

(3, 5, 4, 6)

>>>

Copy
Find the index of an item of the tuple
>>> #create a tuple

>>> tuplex = tuple("index tuple")

>>> print(tuplex)

('i', 'n', 'd', 'e', 'x', ' ', 't', 'u', 'p', 'l', 'e')

>>> #get index of the first item whose value is passed as parameter

>>> index = tuplex.index("p")

>>> print(index)

>>> #define the index from which you want to search

>>> index = tuplex.index("p", 5)

>>> print(index)

8
>>> #define the segment of the tuple to be searched

>>> index = tuplex.index("e", 3, 6)

>>> print(index)

>>> #if item not exists in the tuple return ValueError Exception

>>> index = tuplex.index("y")

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

ValueError: tuple.index(x): x not in tuple

>>>

Copy
The size of a tuple
>>> tuplex = tuple("w3resource") #create a tuple

>>> print(tuplex)

('w', '3', 'r', 'e', 's', 'o', 'u', 'r', 'c', 'e')

>>> #use the len() function to known the length of tuple.

>>> print(len(tuplex))

10

>>>

Copy
How operators + and * are used with a Python tuple?
>>> #create a tuple

>>> tuplex = 5, #create a tuple

>>> #The * operator allow repeat the items in the tuple

>>> print(tuplex * 6)

(5, 5, 5, 5, 5, 5)

>>> #create a tuple with repeated items.

>>> tuplex = (5, 10, 15) * 4


>>> print(tuplex)

(5, 10, 15, 5, 10, 15, 5, 10, 15, 5, 10, 15)

>>> #create three tuples

>>> tuplex1 = (3, 6, 9, 12, 15)

>>> tuplex2 = ("w", 3, "r", "s", "o", "u", "r", "c", "e")

>>> tuplex3 = (True, False)

>>> #The + operator allow create a tuple joining two or more tuples

>>> tuplex = tuplex1 + tuplex2 + tuplex3

>>> print(tuplex)

(3, 6, 9, 12, 15, 'w', 3, 'r', 's', 'o', 'u', 'r', 'c', 'e', True, False)

>>>

Copy
Slice of a tuple using step parameter
>>> #create a tuple

>>> tuplex = tuple("HELLO WORLD")

>>> print(tuplex)

('H', 'E', 'L', 'L', 'O', ' ', 'W', 'O', 'R', 'L', 'D')

>>> #step specify an increment between the elements to cut of the tuple.

>>> _slice = tuplex[2:9:2] #tuple[start:stop:step]

>>> print(_slice)

('L', 'O', 'W', 'R')

>>> #returns a tuple with a jump every 3 items.

>>> _slice = tuplex[::4]

>>> print(_slice)

('H', 'O', 'R')

>>> #when step is negative the jump is made back

>>> _slice = tuplex[9:2:-4]

>>> print(_slice)
('L', ' ')

>>> #when step is negative the jump is made back

>>> _slice = tuplex[9:2:-3]

>>> print(_slice)

('L', 'W', 'L')

>>>

Copy
Modify items of a tuple
>>> #create a tuple

>>> tuplex = ("w", 3, "r", [], False)

>>> print(tuplex)

('w', 3, 'r', [], False)

>>> #tuples are immutable, so you can not modify items which are also immutable, as
str, boolean, numbers etc.

>>> tuplex[3].append(200)

>>> print(tuplex)

('w', 3, 'r', [200], False)

>>>

Copy
Previous: Python Dictionary

Python Sets
Last update on February 28 2020 12:08:08 (UTC/GMT +8 hours)

Sets
A set object is an unordered collection of distinct hashable objects. It is
commonly used in membership testing, removing duplicates from a sequence,
and computing mathematical operations such as intersection, union, difference,
and symmetric difference.
Sets support x in the set, len(set), and for x in set like other collections. Set is an
unordered collection and does not record element position or order of insertion.
Sets do not support indexing, slicing, or other sequence-like behavior.

There are currently two built-in set types, set, and frozenset. The set type is
mutable - the contents can be changed using methods like add() and remove().
Since it is mutable, it has no hash value and cannot be used as either a
dictionary key or as an element of another set. The frozenset type is immutable
and hashable - its contents cannot be altered after it is created; it can, therefore,
be used as a dictionary key or as an element of another set.

Contents:

 Set commands

 Create a set in Python

 Iteration Over Sets

 Add member(s) in Python set

 Remove item(s) from Python set

 Intersection of sets

 Union of sets

 set difference in Python

 Symmetric difference

 issubset and issuperset

 Shallow copy of sets

 Clear sets

 Python Data Types: Sets - Exercises, Practice, Solution

Set: Commands
<set> = set()

<set>.add(<el>)
# Or: <set> |= {<el>}
<set>.update(<collection>)
# Or: <set> |= <set>
<set> = <set>.union(<coll.>)
# Or: <set> | <set>
<set> = <set>.intersection(<coll.>)
# Or: <set> & <set>
<set> = <set>.difference(<coll.>)
# Or: <set> - <set>
<set> = <set>.symmetric_difference(<coll.>)
# Or: <set> ^ <set>
<bool> = <set>.issubset(<coll.>)
# Or: <set> <= <set>
<bool> = <set>.issuperset(<coll.>)
# Or: <set> >= <set>

<el> = <set>.pop()
# Raises KeyError if empty.
<set>.remove(<el>)
# Raises KeyError if missing.
<set>.discard(<el>)
# Doesn't raise an error.
Frozen Set

 Is immutable and hashable.

 That means it can be used as a key in a dictionary or as an element in a set.


<frozenset> = frozenset(<collection>)

Create a set in Python:


>>> #A new empty set

>>> setx = set()

>>> print(setx)

set()

>>> #A non empty set

>>> n = set([0, 1, 2, 3, 4, 5])

>>> print(n)

{0, 1, 2, 3, 4, 5}
>>>

Copy

Iteration Over Sets:


We can move over each of the items in a set using a loop. However, since sets
are unordered, it is undefined which order the iteration will follow.
>>> num_set = set([0, 1, 2, 3, 4, 5])

>>> for n in num_set:

print(n)

>>>

Copy

Add member(s) in Python set:


>>> #A new empty set

>>> color_set = set()

>>> #Add a single member

>>> color_set.add("Red")

>>> print(color_set)

{'Red'}
>>> #Add multiple items

>>> color_set.update(["Blue", "Green"])

>>> print(color_set)

{'Red', 'Blue', 'Green'}

>>>

Copy

Remove item(s) from Python set:


pop(), remove() and discard() functions are used to remove individual item from a
Python set. See the following examples :

pop() function:
>>> num_set = set([0, 1, 2, 3, 4, 5])

>>> num_set.pop()

>>> print(num_set)

{1, 2, 3, 4, 5}

>>> num_set.pop()

>>> print(num_set)

{2, 3, 4, 5}

>>>

Copy
remove() function:
>>> num_set = set([0, 1, 2, 3, 4, 5])

>>> num_set.remove(0)

>>> print(num_set)

{1, 2, 3, 4, 5}
>>>

Copy
discard() function:
>>> num_set = set([0, 1, 2, 3, 4, 5])

>>> num_set.discard(3)

>>> print(num_set)

{0, 1, 2, 4, 5}

>>>

Copy

Intersection of sets:
In mathematics, the intersection A ∩ B of two sets A and B is the set that
contains all elements of A that also belong to B (or equivalently, all elements of B
that also belong to A), but no other elements.
>>> #Intersection

>>> setx = set(["green", "blue"])

>>> sety = set(["blue", "yellow"])

>>> setz = setx & sety

>>> print(setz)

{'blue'}

>>>

Copy

Union of sets:
In set theory, the union (denoted by ∪) of a collection of sets is the set of all
distinct elements in the collection. It is one of the fundamental operations through
which sets can be combined and related to each other.
>>> #Union

>>> setx = set(["green", "blue"])

>>> sety = set(["blue", "yellow"])

>>> seta = setx | sety

>>> print (seta)

{'yellow', 'blue', 'green'}

>>>

Copy

Set difference:
>>> setx = set(["green", "blue"])

>>> sety = set(["blue", "yellow"])

>>> setz = setx & sety

>>> print(setz)

{'blue'}

>>> #Set difference

>>> setb = setx - setz

>>> print(setb)

{'green'}

>>>

Copy

Symmetric difference:
>>> setx = set(["green", "blue"])

>>> sety = set(["blue", "yellow"])

>>> #Symmetric difference


>>> setc = setx ^ sety

>>> print(setc)

{'yellow', 'green'}

>>>

Copy

issubset and issuperset:


>>> setx = set(["green", "blue"])

>>> sety = set(["blue", "yellow"])

>>> issubset = setx <= sety

>>> print(issubset)

False

>>> issuperset = setx >= sety

>>> print(issuperset)

False

>>>

Copy
More Example:
>>> setx = set(["green", "blue"])

>>> sety = set(["blue", "green"])

>>> issubset = setx <= sety

>>> print(issubset)

True

>>> issuperset = setx >= sety

>>> print(issuperset)

True

>>>
Copy

Shallow copy of sets:


>>> setx = set(["green", "blue"])

>>> sety = set(["blue", "green"])

>>> #A shallow copy

>>> setd = setx.copy()

>>> print(setd)

{'blue', 'green'}

>>>

Copy

Clear sets:
>>> setx = set(["green", "blue"])

>>> #Clear AKA empty AKA erase

>>> sete = setx.copy()

>>> sete.clear()

>>> print(sete)

set()

>>>

Python: user defined functions


Last update on February 28 2020 12:16:39 (UTC/GMT +8 hours)

Introduction
In all programming and scripting language, a function is a block of program
statements which can be used repetitively in a program. It saves the time of a
developer. In Python concept of function is same as in other languages. There
are some built-in functions which are part of Python. Besides that, we can
defines functions according to our need.

User defined function

 In Python, a user-defined function's declaration begins with the keyword def and followed by
the function name.
 The function may take arguments(s) as input within the opening and closing parentheses,
just after the function name followed by a colon.
 After defining the function name and arguments(s) a block of program statement(s) start at
the next line and these statement(s) must be indented.

Here is the syntax of a user defined function.

Syntax:
def function_name(argument1, argument2, ...) :
    statement_1
    statement_2
    ....
Inside Function Call
<function>(<positional_args>)
# f(0, 0)
<function>(<keyword_args>)
# f(x=0, y=0)
<function>(<positional_args>, <keyword_args>)
# f(0, y=0)

Inside Function Call


def f(<nondefault_args>):
# def f(x, y):
def f(<default_args>):
# def f(x=0, y=0):
def f(<nondefault_args>, <default_args>):
# def f(x, y=0):
Call a function
Calling a function in Python is similar to other programming languages, using the
function name, parenthesis (opening and closing) and parameter(s). See the
syntax, followed by an example.

Syntax:

function_name(arg1, arg2)
Argument combinations:
def f(a, b, c): # f(a=1, b=2, c=3) | f(1, b=2,
c=3) | f(1, 2, b=3) | f(1, 2, 3)
def f(*, a, b, c): # f(a=1, b=2, c=3)
def f(a, *, b, c): # f(a=1, b=2, c=3) | f(1, b=2,
c=3)
def f(a, b, *, c): # f(a=1, b=2, c=3) | f(1, b=2,
c=3) | f(1, 2, c=3)

def f(*args): # f(1, 2, 3)


def f(a, *args): # f(1, 2, 3)
def f(*args, c): # f(1, 2, c=3)
def f(a, *args, c): # f(1, 2, c=3)

def f(**kwargs): # f(a=1, b=2, c=3)


def f(a, **kwargs): # f(a=1, b=2, c=3) | f(1, b=2,
c=3)
def f(*, a, **kwargs): # f(a=1, b=2, c=3)

def f(*args, **kwargs): # f(a=1, b=2, c=3) | f(1, b=2,


c=3) | f(1, 2, c=3) | f(1, 2, 3)
def f(a, *args, **kwargs): # f(a=1, b=2, c=3) | f(1, b=2,
c=3) | f(1, 2, c=3) | f(1, 2, 3)
def f(*args, b, **kwargs): # f(a=1, b=2, c=3) | f(1, b=2,
c=3)
def f(a, *args, c, **kwargs): # f(a=1, b=2, c=3) | f(1, b=2,
c=3) | f(1, 2, c=3)
Example:
def avg_number(x, y):

print("Average of ",x," and ",y, " is ",(x+y)/2)

avg_number(3, 4)
Copy
Output:
Average of 3 and 4 is 3.5
Explanation:

1. Lines 1-2 : Details (definition) of the function.


2. Line 3 : Call the function.
3. Line 1 : Pass parameters : x = 3, y = 4
4. Line 2 : Print the value of two parameters as well as their average value.

Function without arguments:

The following function has no arguments.

def function_name() :
    statement_1
    statement_2
    ....

Example:
def printt():

print("This is Python 3.2 Tutorial")

print("This is Python 3.2 Tutorial")

print("This is Python 3.2 Tutorial")

printt()

Copy
Output:
This is Python 3.2 Tutorial
This is Python 3.2 Tutorial
This is Python 3.2 Tutorial
Explanation:

1. Lines 1-4 : Details (definition) of the function.


2. Line 5 : Call the function.
3. Line 1 : No parameter passes.
4. Line 2-4 : Execute three print statements.

The Return statement in function

In Python the return statement (the word return followed by an expression.) is


used to return a value from a function, return statement without an expression
argument returns none. See the syntax.

def function_name(argument1, argument2, ...) :


    statement_1
    statement_2
    ....
    return expression

function_name(arg1, arg2)

Example:

The following function returns the square of the sum of two numbers.
def nsquare(x, y):

return (x*x + 2*x*y + y*y)

print("The square of the sum of 2 and 3 is : ", nsquare(2, 3))

Copy
Output:
The square of the sum of 2 and 3 is : 25
Explanation:

1. Lines 1-2 : Details (definition) of the function.


2. Line 3 : Call the function within a print statement.
3. Line 1 : Pass the parameters x = 2, y = 3
4. Line 2 : Calculate and return the value of (x + y)2

Default Argument Values


In function's parameters list we can specify a default value(s) for one or more
arguments. A default value can be written in the format "argument1 = value",
therefore we will have the option to declare or not declare a value for those
arguments. See the following example.

Example:

The following function returns the square of the sum of two numbers, where
default value of the second argument is 2.
def nsquare(x, y = 2):

return (x*x + 2*x*y + y*y)

print("The square of the sum of 2 and 2 is : ", nsquare(2))

print("The square of the sum of 2 and 3 is : ", nsquare(2,4))

Copy
Output:
The square of the sum of 2 and 2 is: 16
The square of the sum of 2 and 4 is : 36
Explanation:

Lines 1-2 : Details (definition) of the function.

For first print statement [ Line no 3]


Line 3 : Call the function without a second argument, within a print statement.
Line 1 : Pass the parameters x = 2, default value.
Line 2 : Calculate and return the value of (x + y)2

For second print statement [ Line no 4]


Line 3 : Call the function with all arguments, within a print statement.
Line 1 : Pass the parameters x = 2, y = 4.
Line 2 : Calculate and return the value of (x + y)2

Keyword Arguments:

We have already learned how to use default arguments values, functions can
also be called using keyword arguments. Arguments which are preceded with a
variable name followed by a '=' sign (e.g. var_name=") are called keyword
arguments.

All the keyword arguments passed must match one of the arguments accepted
by the function. You may change the order of appearance of the keyword. See
the following example.

Example:
def marks(english, math = 85, science = 80):

print('Marks in : English is - ', english,', Math - ',math, ', Science - ',science)

marks(71, 77)

marks(65, science = 74)

marks(science = 70, math = 90, english = 75)

Copy
Output:
Marks in : English is - 71 , Math - 77 , Science - 80
Marks in : English is - 65 , Math - 85 , Science - 74
Marks in : English is - 75 , Math - 90 , Science - 70
Explanation:

Line 1: The function named marks has three parameters, there is no default
value in the first parameter (english) but remaining parameters have default
values (math = 85, science = 80).
Line 3: The parameter english gets the value of 71, math gets the value 77 and
science gets the default value of 80.
Line 4: The parameter english gets the value of 65, math gets the default value of
85 and science gets the value of 74 due to keyword arguments.
Line 5: Here we use three keyword arguments and the parameter english gets
the value 75, math gets the value 90 and science gets the value 70.

Arbitrary Argument Lists:

The 'arbitrary argument' list is an another way to pass arguments to a function. In


the function body, these arguments will be wrapped in a tuple and it can be
defined with *args construct. Before this variable, you can define a number of
arguments or no argument.

Example:
def sum(*numbers):

s = 0

for n in numbers:

s += n

return s

print(sum(1,2,3,4))

Copy
Output:
10
Lambda Forms:

In Python, small anonymous (unnamed) functions can be created with lambda


keyword. Lambda forms can be used as an argument to other function where
function objects are required but syntactically they are restricted to a single
expression. A function like this:
def average(x, y):

return (x + y)/2

print(average(4, 3))

Copy
may also be defined using lambda

print((lambda x, y: (x + y)/2)(4, 3))

Copy
Output:
3.5
Python Documentation Strings

In Python, a string literal is used for documenting  a module, 


function, class, or method. You can access string literals by __doc__ (notice the
double underscores) attribute of the object (e.g. my_function.__doc__).

Docstring Conventions :

  - String literal literals must be enclosed with a triple quote. Docstring should be
informative

  - The first line may briefly describe the object's purpose. The line should begin
with a capital letter and ends with a dot.

  - If a documentation string is a muti-line string then the second line should be
blank followed by any detailed explanation starting from the third line.

 See the following example with multi-line docstring.


def avg_number(x, y):

"""Calculate and Print Average of two Numbers.

Created on 29/12/2012. python-docstring-example.py

"""

print("Average of ",x," and ",y, " is ",(x+y)/2)

Copy
 

Python Module
Last update on February 28 2020 12:07:50 (UTC/GMT +8 hours)

Introduction
Modules are a simple way to organize a program which contains program code,
variables etc.. All these definitions and statements are contained in a single
Python file. The name of the module is the name of the file name with .py
extension. Modules are not loaded unless we execute in Python interpreter or
call within a program. In Python, there are modules in a standard library, current
directory or directories containing .py files (in fact each file with .py extension is a
module). To define a module, you can use Python IDLE, Notepad++ or any
suitable text editor. Lets create a file called factorial.py which will create the
factorial (in mathematics, the factorial of n [a positive integer] is the product of all
positive integers less than or equal to n.) of a positive integer as well as some
other jobs in the current directory.

Example:
# factorial.py

def factcal(n): # Create the factorial of a positive integer


fact = 1

while n>0:

fact *= n

n=n-1

if(n<=1):

break

else: # Display the message if n is not a positive integer.

print('Input a correct number....')

return

return fact

def factdata(n): # return the numbers of factorial x

result = []

while n>0:

result.append(n)

n = n - 1

if(n==0):

break

else: # Display the message if n is not a positive integer.

print('Input a correct number....')

return

return result

Copy
Importing a module:

In order to use a module, use import statement. Go to the Python interpreter and
execute the following command :
 

There are two functions factcal(n) and factdata(n) are defined in factorial.py.


Using the module name we can access the functions. functions factcal(5) creates
the factorial of 5 and factdata(5) shows the numbers involved in factorial 5.

In the above example instead of factorial.factcal(n) or factorial.factdata(n) we can


assign it to a local name. See the following codes, we assign factorial.factcal
into fumber and factorial.factdata into fdata.
 

In Python, a module name (as a string) is stored within a module which is


available as the value of the global variable __name__.

from..import statement

from .. import statement is used to import selective names(s) or all names that a
module defines. See the following codes.
 

In above example when we execute factdata(9), an error arise as we only


import factcal. To avoid this type of situation import all name(s) with import
command adding with a * symbol.

Executing modules as scripts:

To run a Python module as a script use the following syntax.

python filename <arguments>


The program code in the module will be executed with the __name__ set to
"__main__" which means adding some additional code at the end of the module.
See the source code of script-factorial.py.
# script-factorial.py

def factcal(n):

# Create the factorial of a positive integer

fact = 1

while n>0:

fact *= n

n=n-1
if(n<=1):

break

else:

# Display the message if n is not a positive integer.

print('Input a correct number....')

return

print(fact)

def factdata(n): # return the numbers of factorial x

result = []

while n>0:

result.append(n)

n = n - 1

if(n==0):

break

else:

# Display the message if n is not a positive integer.

print('Input a correct number....')

return

print(result)

if __name__ == "__main__":

import sys

factcal(int(sys.argv[1]))

factdata(int(sys.argv[2]))

Copy
Now execute the file at the command prompt (here in windows).
 

Modules Path:

 In the directory ,the script is saved or in the current directory.

 in PYTHONPATH (a list of directory names), default search path for module files.
PYTHONPATH is an environment variable. You will get it using 'env' command in UNIX-
based operating system or in the properties of My Computer in windows system.

 the installation-dependent default.

Standard Module:

Python comes with numerous modules.

Python has many standard modules as a library. These are aimed to add
efficiency or to access operating system primitives. Some of the modules depend
upon the operating system.

sys is a Python Standard module which is very useful. It is built into every Python
interpreter.

The dir() function:

The built-in function dir() is used to get the names (a sorted list of strings), a
module is defined. Check it into Python shell.
 

Python Calendar Module


Last update on February 28 2020 12:40:58 (UTC/GMT +8 hours)

Python Calendar
This module allows you to output calendars like the Unix cal program and
provides additional useful functions related to the calendar. By default, these
calendars have Monday as the first day of the week, and Sunday as the last (the
European convention). Use setfirstweekday() to set the first day of the week to
Sunday (6) or to any other weekday. Parameters that specify dates are given as
integers. For related functionality, see also the datetime and time modules.

Calender:
Name Description

iterweekdays() method Return an iterator for the weekdays numbers that will be used for one week.

itermonthdates() method The itermonthdates() method is used to return an iterator for the month month (1

itermonthdays2() method The itermonthdays2() method is used to return an iterator for the month month in

itermonthdays() method The itermonthdays() method is used to return an iterator for the month month in

monthdatescalendar() method The monthdatescalendar() method is used to return a list of the weeks in the mon
of seven datetime.date objects.

monthdays2calendar() method The monthdays2calendar() method is used to return a list of the weeks in the mon
of seven tuples of day numbers and weekday numbers.

monthdayscalendar() method The monthdayscalendar() method is used to return a list of the weeks in the mont
of seven day numbers.

yeardatescalendar() method The yeardatescalendar() method is used to return the data for the specified year r
month rows.

yeardays2calendar() method The yeardays2calendar() method is used to return the data for the specified year r
yeardatescalendar()).

yeardayscalendar() method The yeardayscalendar() method is used to return the data for the specified year re

text-calendar-formatmonth() The formatmonth() method is used to return a month’s calendar in a multi-line str
method

text-calendar-prmonth() method The prmonth() method is used to Print a month’s calendar as returned by formatm
text-calendar-formatyear() method The formatyear() method is used to return a m-column calendar for an entire year

text-calendar-pryear() method The pryear() method is used to Print the calendar for an entire year as returned by

html-calendar-formatmonth() The formatmonth() method is used to return a month’s calendar as an HTML table
method

html-calendar-formatyear()method The formatyear() method is used to return a year’s calendar as an HTML table.

html-calendar-formatyearpage() The formatyearpage() method is used to return a year’s calendar as a complete HT


method

setfirstweekday() method Sets the weekday (0 is Monday, 6 is Sunday) to start each week.

firstweekday() method The firstweekday() method is used to returns the current setting for the weekday

isleap() method The isleap() method is used to returns True if year is a leap year, otherwise False.

leapdays() method The leapdays() method is used to returns the number of leap years in the range fro

weekday() method The weekday() method is used to returns the day of the week (0 is Monday) for ye

weekheader() method The weekheader() method is used to return a header containing abbreviated week
one weekday.

monthrange() method The monthrange() method is used to returns weekday of first day of the month an
and month.

monthcalendar() method The monthrange() method is used to returns a matrix representing a month’s cale

prmonth() method The prmonth() method is used to prints a month’s calendar as returned by month
month() method The month() method is used to returns a month’s calendar in a multi-line string us

prcal() method The prcal() method is used to prints the calendar for an entire year as returned by

calendar() method The calendar() method is used to returns a 3-column calendar for an entire year as
TextCalendar class.

Python Calendar Module: iterweekdays()


method
Last update on February 28 2020 12:40:22 (UTC/GMT +8 hours)

iterweekdays() method
The iterweekdays() method returns an iterator for the weekday numbers that will
be used for one week. The first number from the iterator will be the same as the
number returned by firstweekday().

Syntax
iterweekdays()
Example -1: Python iterweekdays() method
import calendar

#set firstweekday=0

cal= calendar.Calendar(firstweekday=0)

for x in cal.iterweekdays():

print(x)

Copy

Output:
0
1
2
3
4
5
6
Example - 2: iterweekdays() method
import calendar

#set firstweekday=1

cal= calendar.Calendar(firstweekday=1)

for x in cal.iterweekdays():

print(x)

Copy

Output:
1
2
3
4
5
6
0
Note: firstweekday() - Return an array for one week of weekday numbers starting
with the configured first one.

Python Calendar Module: iterweekdays()


method
Last update on February 28 2020 12:40:22 (UTC/GMT +8 hours)

iterweekdays() method
The iterweekdays() method returns an iterator for the weekday numbers that will
be used for one week. The first number from the iterator will be the same as the
number returned by firstweekday().

Syntax
iterweekdays()
Example -1: Python iterweekdays() method
import calendar

#set firstweekday=0

cal= calendar.Calendar(firstweekday=0)

for x in cal.iterweekdays():

print(x)

Copy

Output:
0
1
2
3
4
5
6
Example - 2: iterweekdays() method
import calendar

#set firstweekday=1

cal= calendar.Calendar(firstweekday=1)

for x in cal.iterweekdays():

print(x)

Copy

Output:
1
2
3
4
5
6
0
Note: firstweekday() - Return an array for one week of weekday numbers starting
with the configured first one.
Python Calendar Module: itermonthdays2()
method
Last update on February 28 2020 12:40:29 (UTC/GMT +8 hours)

itermonthdays2() method
The itermonthdays2() method is used to get an iterator for the month in the year
similar to itermonthdates(). Days returned will be tuples consisting of a day
number and a week day number.

Syntax
itermonthdays2(year, month)
Parameters

Name Description

year Year for which the calendar should be generated.

month Month for which the calendar should be generated.

Example of Python itermonthdates() method


import calendar

cal= calendar.Calendar()

for x in cal.itermonthdays2(2016, 5):

print(x)

Copy

Output:
(0, 0)
(0, 1)
(0, 2)
(0, 3)
(0, 4)
(0, 5)
(1, 6)
(2, 0)
(3, 1)
(4, 2)
(5, 3)
(6, 4)
(7, 5)
(8, 6)
(9, 0)
(10, 1)
(11, 2)
(12, 3)
(13, 4)
(14, 5)
(15, 6)
(16, 0)
(17, 1)
(18, 2)
(19, 3)
(20, 4)
(21, 5)
(22, 6)
(23, 0)
(24, 1)
(25, 2)
(26, 3)
(27, 4)
(28, 5)
(29, 6)
(30, 0)
(31, 1)
(0, 2)
(0, 3)
(0, 4)
(0, 5)
(0, 6)
Note: itermonthdates

Return an iterator for the month month (1-12) in the year year. This iterator will
return all days (as datetime.date objects) for the month and all days before the
start of the month or after the end of the month that are required to get a
complete week.
Python Calendar Module: itermonthdays()
method
Last update on February 28 2020 12:40:36 (UTC/GMT +8 hours)

itermonthdays() method
The itermonthdays() method returns an iterator of a specified month and a year.
Days returned will simply be day numbers. The method is similar to
itermonthdates().

Syntax:
itermonthdays(year, month)
Parameters:

Name Description

year Year for which the calendar should be generated.

month Month for which the calendar should be generated.

Example of itermonthdays() method


import calendar

cal= calendar.Calendar()

for x in cal.itermonthdays(2016, 5):

print(x)

Copy

Output:
0
0
0
0
0
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
0
0
0
0
0
Note: itermonthdates: Return an iterator for the month month (1-12) in the year
year. This iterator will return all days (as datetime.date objects) for the month and
all days before the start of the month or after the end of the month that are
required to get a complete week.
Other resource : https://www.w3resource.com/python/module/calendar/itermonthdays.php
Python Classes
Last update on February 28 2020 12:14:18 (UTC/GMT +8 hours)

Introduction
The basic idea behind an object-oriented programming (OOP) is to combine both
data and associated procedures (known as methods) into a single unit which
operate on the data. Such a unit is called an object.

Python is an object-oriented language, everything in Python is an object.

We have already worked with some objects in Python, (See Python data type
chapter) for example strings, lists are objects defined by the string and list
classes which are available by default into Python. Let's declare two objects a
string and a list and test their type with type() function.

As string1 is an object, strings "Good Morning" can produce an uppercase or


lowercase version of themselves calling upper() and lower() methods associated
with the string. Check it in the Python IDLE.
 
Note : To see the list of string methods execute the following command in Python IDLE
>>>help(str)

Before introducing classes we must discuss something about local variables,


global statement, and a nonlocal statement as well as Namespaces and scope
rules.

Local Variables:

When a variable is declared inside a function, that variable is accessible only


from that function or statements block where it is declared. The variable has no
relation with any other variable with the same name declared outside the
function, therefore the variable is local to the function. See the following example.
# python-local-variable.py

def function_local(a):

print('a is -> ',a)

a = 50

print('After new value within the function a is -> ',a)

a = 100

function_local(40)

print('Value of a is ->',a)

Copy
Output:
a is -> 40
After new value within the function a is -> 50
Value of a is -> 100
Explanation:

Line No.- 2 : Declared a function function_local(a) with a parameter


Line No.- 3 : Print 'a' uses the value of the parameter. [The value of a is now 100
as we assign a to 100 (Line No. 6) before executing the function (Line No. 7).]
Line No.- 4 : Assign the value 50 to 'a'.
Line No.- 5 : Again print 'a', as a is local within the function, therefore, the value
of a is now 50.
Line No.- 8 : This is the last print statement and 'a' becomes 100. So far what we
have done within the function which has no effect on the function. This is called
the scope of the variable.

global statement:

The purpose of the global statement is to assign a value to a variable which is


declared outside the function. Free variables (See Line No. 06 in the previous
example) may refer to global without declaring global. The syntax of global
statement is -> global var_name1, var_name2, ..
See the following example:
# python-global-variable.py

def function_local():

global a

print('a is -> ',a)

a = 50

print('After new value within the function a is -> ',a)

a = 100

function_local()

print('Value of a is ->',a)

Copy
Output:
a is -> 100
After new value within the function a is -> 50
Value of a is -> 50
Explanation:

Line No.- 3 : The variable 'a' is declared as a global variable, therefore the value
of a is now 100.
Line No.- 5 : Assign the value 50 to 'a' and it will hold same value inside and
outside the function unless we assign a new value.

nonlocal statement

The nonlocal statement is used to rebind variables found outside of the


innermost scope. See the following example without a nonlocal statement.
def outside():

a = 10

def inside():

a = 20

print("Inside a ->", a)

inside()

print("outside a->", a)

outside()

Copy
In the above example the first print() statement simply print the value of 'a', which
is 20 as 'a' is local within inside() function. The second print() statement prints the
value 'a', which is 10 as the inside() function has no effect. Now we introduce a
nonlocal statement in inside() function and the code will be:

def outside():

a = 10

def inside():

nonlocal a

a = 20

print("The value of a in inside() function - ", a)

inside()

print("The value of a in outside() function - ", a)

outside()

Copy
The second print() statement prints the value 'a', which is 20 as the variable 'a' is
rebound..

Python Scopes and Namespaces:

In general, a namespace is a naming system to create unique names. In daily


experience, we see railway stations, airports, the capital of various states, the
directory structure of filesystems have unique names. As of other programming
language Python uses namespaces for identifiers.

A namespace is a mapping from names to objects.

  - For example 'a' maps to [1, 2, 3] or 'a' maps to the value 25.

  - Most namespaces currently implemented as Python dictionaries (containing


the names and values of the objects).

  - Names in different namespaces have absolutely no relationship (e.g. the


variable 'a' can be bound to different objects in different namespaces).

  - Examples of the namespace : The global name of a module, local names in a


function invocation, built-in names (containing functions such as min()), attributes
of an object.

Python creates namespaces at different times.

  - The built-in namespace is created when Python interpreter starts and is never
deleted.
  - The global namespace for a module is created when the module is called and
last until the interpreter quits.

  - The local namespace for a function is created when the function is called and
deleted when the function returns.

A scope is a textual region of a Python program where a namespace is directly


accessible. The scopes in python are as follows:

  - The local scope, searched first, contains the local name.

  - Enclosing scope (in an enclosing function) contains non-local and non-global


names.

  - The current module's global names.

  - The outermost scope is the namespace containing built-in names.

Defining a class:

In object oriented programming classes and objects are the main features. A
class creates a new data type and objects are instances of a class which follows
the definition given inside the class. Here is a simple form of class definition.
class Student:
    Statement-1
    Statement-1
    ....
    ....
    ....
    Statement-n

A class definition started with the keyword 'class' followed by the name of the
class and a colon.

The statements within a class definition may be function definitions, data


members or other statements.

When a class definition is entered, a new namespace is created, and used as the
local scope.

Creating a Class:
Here we create a simple class using class keyword followed by the class name
(Student) which follows an indented block of segments (student class, roll no.,
name).
#studentdetails.py

class Student:

stu_class = 'V'

stu_roll_no = 12

stu_name = "David"

Copy

Class Objects:

There are two kind of operations class objects supports : attribute references and
instantiation. Attribute references use the standard syntax, obj.name for all
attribute references in Python. Therefore if the class definition (add a method in
previous example) look like this
#studentdetails1.py

class Student:

"""A simple example class"""

stu_class = 'V'

stu_roll_no = 12

stu_name = "David"

def messg(self):

return 'New Session will start soon.'

Copy

then Student.stu_class, Student.stu_roll_no, Student.stu_name are valid attribute


reference and returns 'V', 12, 'David'. Student.messg returns a function object. In
Python self is a name for the first argument of a method which is different from
ordinary function. Rather than passing the object as a parameter in a method the
word self refers to the object itself. For example if a method is defined as
avg(self, x, y, z), it should be called as a.avg(x, y, z). See the output of the
attributes in Python Shell.

__doc__ is also a valid attribute which returns the docstring of the class.

__init__ method:

There are many method names in Python which have special importance. A
class may define a special method named __init__ which does some initialization
work and serves as a constructor for the class. Like other functions or methods
__init__ can take any number of arguments. The __init__ method is run as soon
as an object of a class is instantiated and class instantiation automatically
invokes __init__() for the newly-created class instance. See the following
example a new, initialized instance can be obtained by:
#studentdetailsinit.py

class Student:

"""A simple example class"""

def __init__(self, sclass, sroll, sname):

self.c = sclass
self.r = sroll

self.n = sname

def messg(self):

return 'New Session will start soon.'

Copy

Operators
Addition:
class School:

def __init__(self, *subjects):

self.subjects = list(subjects)

class Subject:

def __add__(self, other):

return School(self, other)

F1, F2 = Subject(), Subject()

F1 + F2
Copy

Output:
<__main__.School object at 0x0000000008B82470>
from pathlib import Path

path = Path('.').parent / 'data'

path.absolute()

Copy

Output:
WindowsPath('C:/Users/User/AppData/Local/Programs/Python/Python37
/data')
Greater / Equality:
class Person:

'''person entity'''

def __init__(self, first_name, surname, age):

self.first_name = first_name

self.surname = surname

self.age = age

def __repr__(self):

return f'Person(first_name={self.first_name}, surname={self.surname},


age={self.age})'

def __lt__(self, other):

return self.age < other.age

data = [

{'first_name':"John", 'surname':'Smith', 'age':13},

{'first_name':"Anne", 'surname':'McNell', 'age':11},


{'first_name':'Mary', 'surname': 'Brown', 'age':14}

results = [Person(**row) for row in data]

print(results)

Copy

Output:
[Person(first_name=John, surname=Smith, age=13),
Person(first_name=Anne, surname=McNell, age=11),
Person(first_name=Mary, surname=Brown, age=14)]
Length:
class School:

def __init__(self, *subjects):

self.subjects = list(subjects)

def __len__(self):

return len(self.subjects)

Sub = School(Subject(), Subject())

print(len(Sub))

Copy

Output:
2
Getitem:
class School:

def __init__(self, *subjects):

self.subjects = list(subjects)

def __getitem__(self, i):


return self.subjects[i]

Sub = School(Subject(), Subject())

print(Sub[0])

Copy

Output:
<__main__.Subject object at 0x0000000007ACC5F8>
Inheritance:

The concept of inheritance provides an important feature to the object-oriented


programming is reuse of code. Inheritance is the process of creating a new class
(derived class) to be based on an existing (base class) one where the new class
inherits all the attributes and methods of the existing class. Following diagram
shows the inheritance of a derived class from the parent (base) class.
Like other object-oriented language, Python allows inheritance from a parent (or
base) class as well as multiple inheritances in which a class inherits attributes
and methods from more than one parent. See the single and multiple inheritance
syntaxes :
class DerivedClassName(BaseClassName):
    Statement-1
    Statement-1
    ....
    ....
    ....
    Statement-n
class DerivedClassName(BaseClassName1, BaseClassName2, BaseClassName3):
    Statement-1
    Statement-1
    ....
    ....
    ....
    Statement-n

Example:

In a company Factory, staff and Office staff have certain common properties - all
have a name, designation, age etc. Thus they can be grouped under a class
called CompanyMember. Apart from sharing those common features, each
subclass has its own characteristic - FactoryStaff gets overtime allowance while
OfficeStaff gets traveling allowance for an office job. The derived classes
( FactoryStaff & OfficeStaff) has its own characteristic and, in addition, they
inherit the properties of the base class (CompanyMember). See the example
code.
# python-inheritance.py

class CompanyMember:

'''Represents Company Member.'''

def __init__(self, name, designation, age):

self.name = name

self.designation = designation

self.age = age

def tell(self):

'''Details of an employee.'''

print('Name: ', self.name,'\nDesignation : ',self.designation,


'\nAge : ',self.age)

class FactoryStaff(CompanyMember):

'''Represents a Factory Staff.'''

def __init__(self, name, designation, age, overtime_allow):

CompanyMember.__init__(self, name, designation, age)

self.overtime_allow = overtime_allow
CompanyMember.tell(self)

print('Overtime Allowance : ',self.overtime_allow)

class OfficeStaff(CompanyMember):

'''Represents a Office Staff.'''

def __init__(self, name, designation, age, travelling_allow):

CompanyMember.__init__(self, name, designation, age)

self.marks = travelling_allow

CompanyMember.tell(self)

print('Traveling Allowance : ',self.travelling_allow)

Copy

Now execute the class in Python Shell and see the output.

Python: Built-in Functions


Last update on February 28 2020 12:30:14 (UTC/GMT +8 hours)

Built-in Functions
The Python interpreter has a number of functions and types built into it that are
always available. They are listed here in alphabetical order.

Name Description

abs() The abs() function is used to get the absolute (positive) value of a given number.

all() The all() function is used to test whether all elements of an iterable are true or not.

any() The any() function returns True if any element of the iterable is true. The function returns False if the i

ascii() The ascii() function returns a string containing a printable representation (escape the non-ASCII charac

bin() The bin() function is used to convert an integer number to a binary string. The result is a valid Python e

bool() The bool() function is used to convert a value to a Boolean.

bytearray() The bytearray() function is used to get a bytearray object.

bytes() The bytes() function is used to get a new 'bytes' object.

callable() The callable() function returns True if the object argument appears callable, False if not.

chr() The chr() function returns the string representing a character whose Unicode codepoint is the integer.

classmethod() The classmethod() function is used to convert a method into a class method.
complie() The compile() function is used to compile the source into a code.

complex() The complex() function is used to create a complex number or convert a string or number to a comple

delattr() The delattr() function is used to delete the specified attribute from the specified object.

dict() The dict() function is used to create a new dictionary.

dir() The dir() function returns all properties and methods of the specified object, without the values. The f
even built-in properties which are default for all object.

divmod() The divmod() function takes two non complex numbers as arguments and return a pair of numbers co
using integer division. With mixed operand types, the rules for binary arithmetic operators apply.

enumerate() The enumerate() function returns an enumerate object. iterable must be a sequence, an iterator, or so

eval() The eval() function is used to evaluate the specified expression. If the expression is a correct Python st

exec() The exec() function is used to execute the specified Python code. object must be either a string or a co

filter() The filter() function construct an iterator from those elements of iterable for which function returns tr

float() The float() function is used to convert the specified value into a floating point number.

format() The format() function is used to format a specified value into a specified format.

frozenset() The frozenset() function returns a new frozenset object, optionally with elements taken from iterable.

getattr() The getattr() function returns the value of the named attribute of object and name must be a string

globals() The globals() function returns a dictionary representing the current global symbol table.
hash() The hash() function returns the hash value of the object (if it has one).

help() The help() function is used to execute the built-in help system.

hex() The hex() function converts an integer number to a lowercase hexadecimal string prefixed with "0x".

id() The id() function is used to get the identity of an object.

input() The input() function allows user input. If the prompt argument is present, it is written to standard outp

int() The int() function converts the specified value into an integer number.

isinstance() The isinstance() function returns true if the object argument is an instance of the classinfo argument, o

issubclass() The issubclass() function returns true if the specified object is a subclass of the specified object, otherw

iter() The iter() function returns an iterator object.

len() The len() function is used to get the length of an object.

list() The list() function is used to create a list object (list is actually a mutable sequence type).

locals() The locals() function is used to get the local symbol table as a dictionary. Free variables are returned b
not in class blocks.

map() The map() function is used to execute a specified function for each item in a inerrable.

max() The max() function is used to find the item with the largest value in an iterable.

memoryview() The memoryview() function is used to get a memory view object from a specified object.
min() The min() function is used to find the item with the smallest value in an iterable.

next() The next() function is used to get the next item in an iterator.

object() The object() function is used to create an empty object.

oct() The oct() function is used to convert an integer number to an octal string.

open() The open() function is used to open a file and returns it as a file object.

ord() The ord() function is used to get an integer representing the Unicode code point of that character.

pow() The pow() function is used to get the value of x to the power of y (xy). If z is present, return x to the po
pow(x, y) % z).

print() The print() function is used to print objects to the text stream file, separated by sep and followed by e
keyword arguments.

property() The property() function return a property attribute.

range() The range() function is used to get a sequence of numbers, starting from 0 by default, and increments

repr() The repr() function returns a string containing a printable representation of an object.

reversed() The reversed() function is used to get a reverse iterator.

round() The round() function returns the rounded floating point value number, rounded to ndigits digits after t
to zero.

set() The set() function is used to create a set object.

setattr() The setattr() function is used to set the value of the specified attribute of the specified object.
slice() The slice() function is used to get a slice object representing the set of indices specified by range(start,

sorted() The sorted() function is used to get a new sorted list from the items in iterable.

str() The str() function is used to convert the specified value into a string.

sum() The sum() function is used to get the sum of all items in an iterable.

tuple() The tuple() function is used to create a tuple in Python. Iterable may be a sequence, a container that s

type() The type() function is used to get the type of an object.

vars The vars() function is used to get the __dict__ attribute of the given object.

zip() The zip() function is used to make an iterator that aggregates elements from each of the iterables.

https://www.w3resource.com/python/built-in-function/abs.php

Python: Module Index


Last update on February 28 2020 12:36:24 (UTC/GMT +8 hours)

Module Index

Name Description

abc Abstract base classes according to PEP 3119.


aifc Read and write audio files in AIFF or AIFC format.

argparse Command-line option and argument parsing library.

array Space efficient arrays of uniformly typed numeric values.

ast Abstract Syntax Tree classes and manipulation.

asynchat Support for asynchronous command/response protocols.

asyncio Asynchronous I/O.

asyncore A base class for developing asynchronous socket handling services.

atexit Register and execute cleanup functions.

audioop Manipulate raw audio data.

base64 RFC 3548: Base16, Base32, Base64 Data Encodings; Base85 and Ascii85

bdb Debugger framework.

binascii Tools for converting between binary and various ASCII-encoded binary.

binhex Encode and decode files in binhex4 format

bisect Array bisection algorithms for binary searching.

builtins The module that provides the built-in namespace.

bz2 Interfaces for bzip2 compression and decompression.


calendar Functions for working with calendars, including some emulation of the Unix cal program

cgi Helpers for running Python scripts via the Common Gateway Interface.

cgitb Configurable traceback handler for CGI scripts.

chunk Module to read IFF chunks.

cmath Mathematical functions for complex numbers.

cmd Build line-oriented command interpreters.

code Facilities to implement read-eval-print loops.

codes Encode and decode data and streams.

codeop Compile (possibly incomplete) Python code.

collections Container datatypes

colorsys Conversion functions between RGB and other color systems.

compileall Tools for byte-compiling all Python source files in a directory tree.

configparser Configuration file parser.

contextlib Utilities for with-statement contexts.

contextvars Context Variables


copy Shallow and deep copy operations.

copyreg Register pickle support functions.

cProfile This function takes a single argument that can be passed to the exec() function, and an o
executes:

crypy(Unix) The crypt() function used to check Unix passwords.

csv Write and read tabular data to and from delimited files.

ctypes A foreign function library for Python.

map() The map() function is used to execute a specified function for each item in a inerrable.

.curses(Unix) An interface to the curses library, providing portable terminal handling.

dataclasses Generate special methods on user-defined classes.

datetime Basic date and time types.

.dbm Interfaces to various Unix "database" formats.

decimal Implementation of the General Decimal Arithmetic Specification.

difflib Helpers for computing differences between objects.

dis Disassembler for Python bytecode.


.distutils Support for building and installing Python modules into an existing Python installation.

doctest Test pieces of code within docstrings.

dummy_threading Drop-in replacement for the threading module.

.email Package supporting the parsing, manipulating, and generating email messages.

ensurepip Bootstrapping the "pip" installer into an existing Python installation or virtual environme

enum The repr() function returns a string containing a printable representation of an object.

errno Standard errno system symbols.

faulthandler Dump the Python traceback.

fcntl (Unix) The fcntl() and ioctl() system calls.

filecmp The setattr() function is used to set the value of the specified attribute of the specified o

fileinput Loop over standard input or a list of files.

fnmatch Unix shell style filename pattern matching.

fractions Rational numbers.

ftplib The sum() function is used to get the sum of all items in an iterable.

functools Higher-order functions and operations on callable objects.

gc Interface to the cycle-detecting garbage collector.


getopt Portable parser for command line options; support both short and long option names.

getpass Portable reading of passwords and retrieval of the userid.

gettext Multilingual internationalization services.

glob Unix shell style pathname pattern expansion.

grp(Unix) The group database (getgrnam() and friends).

gzip Interfaces for gzip compression and decompression using file objects.

hashlib Secure hash and message digest algorithms.

heapq Heap queue algorithm (a.k.a. priority queue).

hmac Keyed-Hashing for Message Authentication (HMAC) implementation

.html Helpers for manipulating HTML.

.http HTTP status codes and messages

imaplib IMAP4 protocol client (requires sockets).

imghdr Determine the type of image contained in a file or byte stream.

importlib The implementation of the import machinery.

inspect Extract information and source code from live objects.


io Core tools for working with streams.

ipaddress IPv4/IPv6 manipulation library.

itertools Functions creating iterators for efficient looping.

.json Encode and decode the JSON format

keyword Test whether a string is a keyword in Python.

lib2to3 the 2to3 library

linecache This module provides random access to individual lines from text files.

locale Internationalization services.

logging Flexible event logging system for applications.

lzma A Python wrapper for the liblzma compression library.

macpath Mac OS 9 path manipulation functions.

mailbox Manipulate mailboxes in various formats

mailcap Mailcap file handling.

marshal Convert Python objects to streams of bytes and back (with different constraints).

math Mathematical functions (sin() etc.).


mimetypes Mapping of filename extensions to MIME types.

mmap Interface to memory-mapped files for Unix and Windows.

modulefinder Find modules used by a script.

mslib(windows) Creation of Microsoft Installer files, and CAB files.

msvcrt(windows) Miscellaneous useful routines from the MS VC++ runtime.

.multiprocessing Process-based parallelism.

netrc Loading of .netrc files.

nis(Unix) Interface to Sun's NIS (Yellow Pages) library.

nntplib NNTP protocol client (requires sockets).

numbers Numeric abstract base classes (Complex, Real, Integral, etc.).

operator Functions corresponding to the standard operators.

.os Miscellaneous operating system interfaces.

ossaudiodev(Linux, FreeBSD) Access to OSS-compatible audio devices.

parser Access parse trees for Python source code.

pathlib Object-oriented filesystem paths


pdb The Python debugger for interactive interpreters.

pickle Convert Python objects to streams of bytes and back.

pickletools Contains extensive comments about the pickle protocols and pickle-machine opcodes, a

pipes(Unix) A Python interface to Unix shell pipelines.

pkgutil Utilities for the import system.

platform pkgutil

plistlib Generate and parse Mac OS X plist files.

poplib POP3 protocol client (requires sockets).

posix(Umix The most common POSIX system calls (normally used via module os).

pprint Data pretty printer

profile Python source profiler.

pstats Statistics object for use with the profiler

pty(Linux) Pseudo-Terminal Handling for Linux.

pwd(Unix) The password database (getpwnam() and friends).

py_compile Generate byte-code files from Python source files.


pyclbr Supports information extraction for a Python class browser.

pydoc Documentation generator and online help system.

queue A synchronized queue class.

quopri Encode and decode files using the MIME quoted-printable encoding.

random Generate pseudo-random numbers with various common distributions.

re Regular expression operations.

readline(Unix) GNU readline support for Python.

reprlib Alternate repr() implementation with size limits.

resource(Unix) An interface to provide resource usage information on the current process.

rlcompleter Python identifier completion, suitable for the GNU readline library.

runpy Locate and run Python modules without importing them first.

sched General purpose event scheduler.

secrets Generate secure random numbers for managing secrets.

select Wait for I/O completion on multiple streams.

selectors High-level I/O multiplexing.


shelve Python object persistence.

shlex Simple lexical analysis for Unix shell-like languages.

shutil High-level file operations, including copying.

signal Set handlers for asynchronous events.

site Module responsible for site-specific configuration.

smtpd A SMTP server implementation in Python.

smtplib SMTP protocol client (requires sockets).

sndhdr Determine type of a sound file.

socket Low-level networking interface

socketserver A framework for network servers.

spwd(Unix) The shadow password database (getspnam() and friends).

sqlite3 A DB-API 2.0 implementation using SQLite 3.x.

Ssl TLS/SSL wrapper for socket objects

stat Utilities for interpreting the results of os.stat(), os.lstat() and os.fstat().
statistics mathematical statistics functions

string Common string operations.

stringprep String preparation, as per RFC 3453

struct Interpret bytes as packed binary data.

subprocess Subprocess management.

sunau Provide an interface to the Sun AU sound format.

symbol Constants representing internal nodes of the parse tree.

symtable Interface to the compiler's internal symbol tables.

sys Access system-specific parameters and functions.

sysconfig Python's configuration information

syslog(Unix) An interface to the Unix syslog library routines.

Python API
Top-level functions

xlwings.view(obj, sheet=None)
Opens a new workbook and displays an object on its first sheet by default. If you
provide a sheet object, it will clear the sheet before displaying the object on the
existing sheet.

 obj (any type with built-in converter) – the object to display,


Parameters e.g. numbers, strings, lists, numpy arrays, pandas dataframes
:
 sheet (Sheet,  default None) – Sheet object. If none provided,
the first sheet of a new workbook is used.

Examples
>>> import xlwings as xw
>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
>>> xw.view(df)
New in version 0.7.1.

Object model
Apps
classxlwings.main.Apps(impl)
A collection of all  app  objects:

>>> import xlwings as xw


>>> xw.apps
Apps([<Excel App 1668>, <Excel App 1644>])
active

Returns the active app.

New in version 0.9.0.

add()

Creates a new App. The new App becomes the active one. Returns an App object.

count

Returns the number of apps.

New in version 0.9.0.

keys()
Provides the PIDs of the Excel instances that act as keys in the Apps collection.

New in version 0.13.0.

App
classxlwings.App(visible=None, spec=None, add_book=True, impl=None)

An app corresponds to an Excel instance. New Excel instances can be fired up like
so:

>>> import xlwings as xw


>>> app1 = xw.App()
>>> app2 = xw.App()
An app object is a member of the  apps  collection:

>>> xw.apps
Apps([<Excel App 1668>, <Excel App 1644>])
>>> xw.apps[1668] # get the available PIDs via xw.apps.keys()
<Excel App 1668>
>>> xw.apps.active
<Excel App 1668>

 visible (bool,  default None) – Returns or sets a boolean value


that determines whether the app is visible. The default leaves
the state unchanged or sets visible=True if the object doesn’t
exist yet.
 spec (str,  default None) –
Paramet Mac-only, use the full path to the Excel application,
ers:
e.g.  /Applications/Microsoft Office 2011/Microsoft Excel  or  /Appl
ications/Microsoft Excel

On Windows, if you want to change the version of Excel that


xlwings talks to, go
to  Control Panel > Programs and Features  and  Repair  the Office
version that you want as default.
Note

On Mac, while xlwings allows you to run multiple instances of Excel, it’s a feature
that is not officially supported by Excel for Mac: Unlike on Windows, Excel will
not ask you to open a read-only version of a file if it is already open in another
instance. This means that you need to watch out yourself so that the same file is
not being overwritten from different instances.
activate(steal_focus=False)
Activates the Excel app.

Parameters steal_focus (bool,  default False) – If True, make frontmost application and


: hand over focus from Python to Excel.

New in version 0.9.0.

api
Returns the native object ( pywin32  or  appscript  obj) of the engine being used.

New in version 0.9.0.

books

A collection of all Book objects that are currently open.

New in version 0.9.0.

calculate()

Calculates all open books.

New in version 0.3.6.

calculation

Returns or sets a calculation value that represents the calculation mode.


Modes:  'manual' ,  'automatic' ,  'semiautomatic'

Examples
>>> import xlwings as xw
>>> wb = xw.Book()
>>> wb.app.calculation = 'manual'

Changed in version 0.9.0.

display_alerts

The default value is True. Set this property to False to suppress prompts and alert
messages while code is running; when a message requires a response, Excel
chooses the default response.

New in version 0.9.0.


hwnd

Returns the Window handle (Windows-only).

New in version 0.9.0.

kill()

Forces the Excel app to quit by killing its process.

New in version 0.9.0.

macro(name)

Runs a Sub or Function in Excel VBA that are not part of a specific workbook but
e.g. are part of an add-in.

Parameters name (Name of Sub or Function with or without module name,


: e.g.  'Module1.MyMacro'  or  'MyMacro' ) –

Examples

This VBA function:

Function MySum(x, y)
MySum = x + y
End Function

can be accessed like this:

>>> import xlwings as xw


>>> app = xw.App()
>>> my_sum = app.macro('MySum')
>>> my_sum(1, 2)
3
See also:  Book.macro()

New in version 0.9.0.

pid

Returns the PID of the app.

New in version 0.9.0.

quit()

Quits the application without saving any workbooks.


New in version 0.3.3.

range(cell1, cell2=None)
Range object from the active sheet of the active book, see  Range() .

New in version 0.9.0.

screen_updating

Turn screen updating off to speed up your script. You won’t be able to see what
the script is doing, but it will run faster. Remember to set the screen_updating
property back to True when your script ends.

New in version 0.3.3.

selection

Returns the selected cells as Range.

New in version 0.9.0.

startup_path
Returns the path to  XLSTART  which is where the xlwings add-in gets copied to by
doing  xlwings addin install .

New in version 0.19.4.

status_bar
Gets or sets the value of the status bar. Returns  False  if Excel has control of it.

New in version 0.20.0.

version

Returns the Excel version number object.

Examples
>>> import xlwings as xw
>>> xw.App().version
VersionNumber('15.24')
>>> xw.apps[10559].version.major
15
Changed in version 0.9.0.
visible
Gets or sets the visibility of Excel to  True  or  False .

New in version 0.3.3.

Books
classxlwings.main.Books(impl)
A collection of all  book  objects:

>>> import xlwings as xw


>>> xw.books # active app
Books([<Book [Book1]>, <Book [Book2]>])
>>> xw.apps[10559].books # specific app, get the PIDs via xw.apps.keys()
Books([<Book [Book1]>, <Book [Book2]>])

New in version 0.9.0.

active

Returns the active Book.

add()

Creates a new Book. The new Book becomes the active Book. Returns a Book
object.

open(fullname, update_links=None, read_only=None, format=None, password=None, write_
res_password=None, ignore_read_only_recommended=None, origin=None, delimiter=None, 
editable=None, notify=None, converter=None, add_to_mru=None, local=None, corrupt_load
=None)

Opens a Book if it is not open yet and returns it. If it is already open, it doesn’t
raise an exception but simply returns the Book object.

 fullname (str  or  path-like object) – filename or fully qualified


filename, e.g.  r'C:\path\to\file.xlsx'  or  'file.xlsm' .
Parameters: Without a full path, it looks for the file in the current working
directory.
 Parameters (Other) – see:  xlwings.Book()

Returns: Book

Return Book that has been opened.


type:

Book
classxlwings.Book(fullname=None, update_links=None, read_only=None, format=None, password
=None, write_res_password=None, ignore_read_only_recommended=None, origin=None, delimiter=
None, editable=None, notify=None, converter=None, add_to_mru=None, local=None, corrupt_load=
None, impl=None)
A book object is a member of the  books  collection:

>>> import xlwings as xw


>>> xw.books[0]
<Book [Book1]>
The easiest way to connect to a book is offered by  xw.Book : it looks for the book
in all app instances and returns an error, should the same book be open in
multiple instances. To connect to a book in the active app instance,
use  xw.books  and to refer to a specific app, use:

>>> app = xw.App() # or something like xw.apps[10559] for existing apps, get the PIDs
via xw.apps.keys()
>>> app.books['Book1']

  xw.Book xw.books

New book xw.Book() xw.books.add()

Unsaved book xw.Book('Book1') xw.books['Book1']

Book by xw.Book(r'C:/path/to/file.xl xw.books.open(r'C:/path/to/file.x

(full)name sx') lsx')

Parameters:  fullname (str  or  path-like object,  default None) – Full


path or name (incl. xlsx, xlsm etc.) of existing workbook
or name of an unsaved workbook. Without a full path, it
looks for the file in the current working directory.
 update_links (bool,  default None) – If this argument is
omitted, the user is prompted to specify how links will
be updated
 read_only (bool,  default False) – True to open workbook
in read-only mode
  xw.Book xw.books

 format (str) – If opening a text file, this specifies the


delimiter character
 password (str) – Password to open a protected
workbook
 write_res_password (str) – Password to write to a write-
reserved workbook
 ignore_read_only_recommended (bool,  default False) –
Set to  True  to mute the read-only recommended
message
 origin (int) – For text files only. Specifies where it
originated. Use XlPlatform constants.
 delimiter (str) – If format argument is 6, this specifies
the delimiter.
 editable (bool,  default False) – This option is only for
legacy Microsoft Excel 4.0 addins.
 notify (bool,  default False) – Notify the user when a file
becomes available If the file cannot be opened in
read/write mode.
 converter (int) – The index of the first file converter to
try when opening the file.
 add_to_mru (bool,  default False) – Add this workbook
to the list of recently added workbooks.
 local (bool,  default False) – If  True , saves files against
the language of Excel, otherwise against the language of
VBA. Not supported on macOS.
 corrupt_load (int,  default xlNormalLoad) – Can be one
of xlNormalLoad, xlRepairFile or xlExtractData. Not
supported on macOS.
activate(steal_focus=False)

Activates the book.


Parameters steal_focus (bool,  default False) – If True, make frontmost window and
: hand over focus from Python to Excel.

api
Returns the native object ( pywin32  or  appscript  obj) of the engine being used.

New in version 0.9.0.

app

Returns an app object that represents the creator of the book.

New in version 0.9.0.

classmethodcaller()

References the calling book when the Python function is called from Excel
via  RunPython . Pack it into the function being called from Excel, e.g.:

import xlwings as xw

def my_macro():
wb = xw.Book.caller()
wb.sheets[0].range('A1').value = 1

To be able to easily invoke such code from Python for debugging,


use  xw.Book.set_mock_caller() .

New in version 0.3.0.

close()

Closes the book without saving it.

New in version 0.1.1.

fullname

Returns the name of the object, including its path on disk, as a string. Read-only
String.

macro(name)

Runs a Sub or Function in Excel VBA.

Parameters name (Name of Sub or Function with or without module name,


: e.g.  'Module1.MyMacro'  or  'MyMacro' ) –

Examples

This VBA function:

Function MySum(x, y)
MySum = x + y
End Function
can be accessed like this:

>>> import xlwings as xw


>>> wb = xw.books.active
>>> my_sum = wb.macro('MySum')
>>> my_sum(1, 2)
3
See also:  App.macro()

New in version 0.7.1.

name

Returns the name of the book as str.

names

Returns a names collection that represents all the names in the specified book
(including all sheet-specific names).

Changed in version 0.9.0.

save(path=None)

Saves the Workbook. If a path is being provided, this works like SaveAs() in Excel.
If no path is specified and if the file hasn’t been saved previously, it’s being saved
in the current working directory with the current filename. Existing files are
overwritten without prompting.

Parameters path (str  or  path-like object,  default None) – Full path to the
: workbook

Example
>>> import xlwings as xw
>>> wb = xw.Book()
>>> wb.save()
>>> wb.save(r'C:\path\to\new_file_name.xlsx')
New in version 0.3.1.

selection

Returns the selected cells as Range.

New in version 0.9.0.

set_mock_caller()
Sets the Excel file which is used to mock  xw.Book.caller()  when the code is called
from Python and not from Excel via  RunPython .

Examples
# This code runs unchanged from Excel via RunPython and from Python directly
import os
import xlwings as xw

def my_macro():
sht = xw.Book.caller().sheets[0]
sht.range('A1').value = 'Hello xlwings!'

if __name__ == '__main__':
xw.Book('file.xlsm').set_mock_caller()
my_macro()

New in version 0.3.1.

sheets

Returns a sheets collection that represents all the sheets in the book.

New in version 0.9.0.

Sheets
classxlwings.main.Sheets(impl)
A collection of all  sheet  objects:

>>> import xlwings as xw


>>> xw.sheets # active book
Sheets([<Sheet [Book1]Sheet1>, <Sheet [Book1]Sheet2>])
>>> xw.Book('Book1').sheets # specific book
Sheets([<Sheet [Book1]Sheet1>, <Sheet [Book1]Sheet2>])

New in version 0.9.0.

active
Returns the active Sheet.

add(name=None, before=None, after=None)

Creates a new Sheet and makes it the active sheet.

 name (str,  default None) – Name of the new sheet. If None,


will default to Excel’s default name.
Parameters  before (Sheet,  default None) – An object that specifies the
:
sheet before which the new sheet is added.
 after (Sheet,  default None) – An object that specifies the
sheet after which the new sheet is added.

Sheet
classxlwings.Sheet(sheet=None, impl=None)
A sheet object is a member of the  sheets  collection:

>>> import xlwings as xw


>>> wb = xw.Book()
>>> wb.sheets[0]
<Sheet [Book1]Sheet1>
>>> wb.sheets['Sheet1']
<Sheet [Book1]Sheet1>
>>> wb.sheets.add()
<Sheet [Book1]Sheet2>
Changed in version 0.9.0.

activate()

Activates the Sheet and returns it.

api
Returns the native object ( pywin32  or  appscript  obj) of the engine being used.

New in version 0.9.0.

autofit(axis=None)

Autofits the width of either columns, rows or both on a whole Sheet.

Parameters axis (string,  default None) –


:
 To autofit rows, use one of the following:  rows  or  r
 To autofit columns, use one of the following:  columns  or  c
 To autofit rows and columns, provide no arguments

Examples
>>> import xlwings as xw
>>> wb = xw.Book()
>>> wb.sheets['Sheet1'].autofit('c')
>>> wb.sheets['Sheet1'].autofit('r')
>>> wb.sheets['Sheet1'].autofit()
New in version 0.2.3.

book

Returns the Book of the specified Sheet. Read-only.

cells

Returns a Range object that represents all the cells on the Sheet (not just the cells
that are currently in use).

New in version 0.9.0.

charts
See  Charts

New in version 0.9.0.

clear()

Clears the content and formatting of the whole sheet.

clear_contents()

Clears the content of the whole sheet but leaves the formatting.

delete()

Deletes the Sheet.

index

Returns the index of the Sheet (1-based as in Excel).

name
Gets or sets the name of the Sheet.

names

Returns a names collection that represents all the sheet-specific names (names
defined with the “SheetName!” prefix).

New in version 0.9.0.

pictures
See  Pictures

New in version 0.9.0.

range(cell1, cell2=None)
Returns a Range object from the active sheet of the active book, see  Range() .

New in version 0.9.0.

select()

Selects the Sheet. Select only works on the active book.

New in version 0.9.0.

shapes
See  Shapes

New in version 0.9.0.

used_range

Used Range of Sheet.

Returns:

Return
xw.Range
type:

New in version 0.13.0.


Range
classxlwings.Range(cell1=None, cell2=None, **options)

Returns a Range object that represents a cell or a range of cells.

 cell1 (str  or  tuple  or  Range) – Name of the range in the


upper-left corner in A1 notation or as index-tuple or as name

Parameters or as xw.Range object. It can also specify a range using the


: range operator (a colon), .e.g. ‘A1:B2’
 cell2 (str  or  tuple  or  Range,  default None) – Name of the
range in the lower-right corner in A1 notation or as index-
tuple or as name or as xw.Range object.

Examples

Active Sheet:

import xlwings as xw
xw.Range('A1')
xw.Range('A1:C3')
xw.Range((1,1))
xw.Range((1,1), (3,3))
xw.Range('NamedRange')
xw.Range(xw.Range('A1'), xw.Range('B2'))

Specific Sheet:

xw.books['MyBook.xlsx'].sheets[0].range('A1')
add_hyperlink(address, text_to_display=None, screen_tip=None)

Adds a hyperlink to the specified Range (single Cell)

 address (str) – The address of the hyperlink.


 text_to_display (str,  default None) – The text to be displayed

Parameters for the hyperlink. Defaults to the hyperlink address.


:  screen_tip (str,  default None) – The screen tip to be displayed
when the mouse pointer is paused over the hyperlink. Default
is set to ‘<address> - Click once to follow. Click and hold to
select this cell.’

New in version 0.3.0.

address
Returns a string value that represents the range reference. Use  get_address()  to
be able to provide paramaters.

New in version 0.9.0.

api
Returns the native object ( pywin32  or  appscript  obj) of the engine being used.

New in version 0.9.0.

autofit()

Autofits the width and height of all cells in the range.

 To autofit only the width of the columns


use  xw.Range('A1:B2').columns.autofit()
 To autofit only the height of the rows use  xw.Range('A1:B2').rows.autofit()

Changed in version 0.9.0.

clear()

Clears the content and the formatting of a Range.

clear_contents()

Clears the content of a Range but leaves the formatting.

color

Gets and sets the background color of the specified Range.

To set the color, either use an RGB tuple  (0, 0, 0)  or a color constant. To remove
the background, set the color to  None , see Examples.

Returns: RGB

Return
tuple
type:

Examples
>>> import xlwings as xw
>>> wb = xw.Book()
>>> xw.Range('A1').color = (255,255,255)
>>> xw.Range('A2').color
(255, 255, 255)
>>> xw.Range('A2').color = None
>>> xw.Range('A2').color is None
True
New in version 0.3.0.

column

Returns the number of the first column in the in the specified range. Read-only.

Returns:

Return
Integer
type:

New in version 0.3.5.

column_width

Gets or sets the width, in characters, of a Range. One unit of column width is
equal to the width of one character in the Normal style. For proportional fonts,
the width of the character 0 (zero) is used.

If all columns in the Range have the same width, returns the width. If columns in
the Range have different widths, returns None.

column_width must be in the range: 0 <= column_width <= 255

Note: If the Range is outside the used range of the Worksheet, and columns in
the Range have different widths, returns the width of the first column.

Returns:

Return
float
type:

New in version 0.4.0.

columns
Returns a  RangeColumns  object that represents the columns in the specified range.
New in version 0.9.0.

copy(destination=None)

Copy a range to a destination range or clipboard.

destination (xlwings.Range) – xlwings Range to which the specified range


Parameters:
will be copied. If omitted, the range is copied to the Clipboard.

Returns:

Return
None
type:

count

Returns the number of cells.

current_region

This property returns a Range object representing a range bounded by (but not
including) any combination of blank rows and blank columns or the edges of the
worksheet. It corresponds to  Ctrl-*  on Windows and  Shift-Ctrl-Space  on Mac.

Returns:

Return
Range object
type:

delete(shift=None)

Deletes a cell or range of cells.

shift (str,  default None) – Use  left  or  up . If omitted, Excel decides based
Parameters:
on the shape of the range.

Returns:

Return
None
type:

end(direction)
Returns a Range object that represents the cell at the end of the region that
contains the source range. Equivalent to pressing Ctrl+Up, Ctrl+down, Ctrl+left, or
Ctrl+right.

Parameters direction (One of 'up',  'down',  'right',  'left')


: –

Examples
>>> import xlwings as xw
>>> wb = xw.Book()
>>> xw.Range('A1:B2').value = 1
>>> xw.Range('A1').end('down')
<Range [Book1]Sheet1!$A$2>
>>> xw.Range('B2').end('right')
<Range [Book1]Sheet1!$B$2>

New in version 0.9.0.

expand(mode='table')

Expands the range according to the mode provided. Ignores empty top-left cells
(unlike  Range.end() ).

mode (str,  default 'table') – One of  'table'  (=down and


Parameters:
right),  'down' ,  'right' .

Returns:

Return
Range
type:

Examples
>>> import xlwings as xw
>>> wb = xw.Book()
>>> xw.Range('A1').value = [[None, 1], [2, 3]]
>>> xw.Range('A1').expand().address
$A$1:$B$2
>>> xw.Range('A1').expand('right').address
$A$1:$B$1
New in version 0.9.0.

formula

Gets or sets the formula for the given Range.


formula2

Gets or sets the formula2 for the given Range.

formula_array

Gets or sets an array formula for the given Range.

New in version 0.7.1.

get_address(row_absolute=True, column_absolute=True, include_sheetname=False, exter
nal=False)
Returns the address of the range in the specified format.  address  can be used
instead if none of the defaults need to be changed.

 row_absolute (bool,  default True) – Set to True to return the


row part of the reference as an absolute reference.
 column_absolute (bool,  default True) – Set to True to return
the column part of the reference as an absolute reference.
Parameters:  include_sheetname (bool,  default False) – Set to True to
include the Sheet name in the address. Ignored if
external=True.
 external (bool,  default False) – Set to True to return an
external reference with workbook and worksheet name.

Returns:

Return
type: str

Examples
>>> import xlwings as xw
>>> wb = xw.Book()
>>> xw.Range((1,1)).get_address()
'$A$1'
>>> xw.Range((1,1)).get_address(False, False)
'A1'
>>> xw.Range((1,1), (3,3)).get_address(True, False, True)
'Sheet1!A$1:C$3'
>>> xw.Range((1,1), (3,3)).get_address(True, False, external=True)
'[Book1]Sheet1!A$1:C$3'

New in version 0.2.3.


has_array

Are we part of an Array formula?

height

Returns the height, in points, of a Range. Read-only.

Returns:

Return
float
type:

New in version 0.4.0.

hyperlink

Returns the hyperlink address of the specified Range (single Cell only)

Examples
>>> import xlwings as xw
>>> wb = xw.Book()
>>> xw.Range('A1').value
'www.xlwings.org'
>>> xw.Range('A1').hyperlink
'http://www.xlwings.org'

New in version 0.3.0.

insert(shift=None, copy_origin='format_from_left_or_above')

Insert a cell or range of cells into the sheet.

 shift (str,  default None) – Use  right  or  down . If omitted,


Excel decides based on the shape of the range.
Parameters:  copy_origin (str,  default format_from_left_or_above) –
Use  format_from_left_or_above  or  format_from_right_or_below .
Note that this is not supported on macOS.

Returns:

Return
type: None
last_cell

Returns the bottom right cell of the specified range. Read-only.

Returns:

Return
Range
type:

Example
>>> import xlwings as xw
>>> wb = xw.Book()
>>> rng = xw.Range('A1:E4')
>>> rng.last_cell.row, rng.last_cell.column
(4, 5)
New in version 0.3.5.

left

Returns the distance, in points, from the left edge of column A to the left edge of
the range. Read-only.

Returns:

Return
float
type:

New in version 0.6.0.

merge(across=False)

Creates a merged cell from the specified Range object.

Parameters across (bool,  default False) – True to merge cells in each row of the
: specified Range as separate merged cells.

merge_area

Returns a Range object that represents the merged Range containing the
specified cell. If the specified cell isn’t in a merged range, this property returns the
specified cell.

merge_cells
Returns  True  if the Range contains merged cells, otherwise  False
name

Sets or gets the name of a Range.

New in version 0.4.0.

number_format

Gets and sets the number_format of a Range.

Examples
>>> import xlwings as xw
>>> wb = xw.Book()
>>> xw.Range('A1').number_format
'General'
>>> xw.Range('A1:C3').number_format = '0.00%'
>>> xw.Range('A1:C3').number_format
'0.00%'
New in version 0.2.3.

offset(row_offset=0, column_offset=0)

Returns a Range object that represents a Range that’s offset from the specified
range.

Returns: Range object

Return type: Range

New in version 0.3.0.

options(convert=None, **options)

Allows you to set a converter and their options. Converters define how Excel
Ranges and their values are being converted both during reading and writing
operations. If no explicit converter is specified, the base converter is being
applied, see Converters and Options.

convert (object, default None) – A converter,


Parameters: e.g.  dict ,  np.array ,  pd.DataFrame ,  pd.Series , defaults to default
converter

Keyword Arguments:
 ndim (int,  default None) – number of dimensions
 numbers (type,  default None) – type of numbers, e.g.  int
 dates (type,  default None) – e.g.  datetime.date  defaults
to  datetime.datetime
 empty (object,  default None) – transformation of empty cells
 
 transpose (Boolean,  default False) – transpose values
 expand (str,  default None) –

One of  'table' ,  'down' ,  'right'

=> For converter-specific options, see Converters and Options.

Returns:

Return
type: Range object

New in version 0.7.0.

paste(paste=None, operation=None, skip_blanks=False, transpose=False)

Pastes a range from the clipboard into the specified range.

 paste (str,  default None) – One


of  all_merging_conditional_formats ,  all ,  all_except_borders ,  all_usi
ng_source_theme ,  column_widths ,  comments ,  formats ,  formulas ,  formul
as_and_number_formats ,  validation ,  values ,  values_and_number_formats
Para .
met
 operation (str,  default None) – One of “add”, “divide”, “multiply”,
ers:
“subtract”.
 skip_blanks (bool,  default False) – Set to  True  to skip over blank cells
 transpose (bool,  default False) – Set to  True  to transpose rows and
columns.

Retu
rns:

Retu None
rn
type
:

raw_value

Gets and sets the values directly as delivered from/accepted by the engine that is
being used ( pywin32  or  appscript ) without going through any of xlwings’ data
cleaning/converting. This can be helpful if speed is an issue but naturally will be
engine specific, i.e. might remove the cross-platform compatibility.

resize(row_size=None, column_size=None)

Resizes the specified Range

 row_size (int > 0) – The number of rows in the new range (if


None, the number of rows in the range is unchanged).
Parameters:  column_size (int > 0) – The number of columns in the new
range (if None, the number of columns in the range is
unchanged).

Returns: Range object

Return
type: Range

New in version 0.3.0.

row

Returns the number of the first row in the specified range. Read-only.

Returns:

Return
Integer
type:

New in version 0.3.5.

row_height
Gets or sets the height, in points, of a Range. If all rows in the Range have the
same height, returns the height. If rows in the Range have different heights,
returns None.

row_height must be in the range: 0 <= row_height <= 409.5

Note: If the Range is outside the used range of the Worksheet, and rows in the
Range have different heights, returns the height of the first row.

Returns:

Return
float
type:

New in version 0.4.0.

rows
Returns a  RangeRows  object that represents the rows in the specified range.

New in version 0.9.0.

select()

Selects the range. Select only works on the active book.

New in version 0.9.0.

shape

Tuple of Range dimensions.

New in version 0.3.0.

sheet

Returns the Sheet object to which the Range belongs.

New in version 0.9.0.

size

Number of elements in the Range.


New in version 0.3.0.

top

Returns the distance, in points, from the top edge of row 1 to the top edge of the
range. Read-only.

Returns:

Return
float
type:

New in version 0.6.0.

unmerge()

Separates a merged area into individual cells.

value

Gets and sets the values for the given Range.

Returns: object

Return returned object depends on the converter being used,


type: see  xlwings.Range.options()

width

Returns the width, in points, of a Range. Read-only.

Returns:

Return
float
type:

New in version 0.4.0.

RangeRows
classxlwings.RangeRows(rng)

Represents the rows of a range. Do not construct this class directly,


use  Range.rows  instead.
Example
import xlwings as xw

rng = xw.Range('A1:C4')

assert len(rng.rows) == 4 # or rng.rows.count

rng.rows[0].value = 'a'

assert rng.rows[2] == xw.Range('A3:C3')


assert rng.rows(2) == xw.Range('A2:C2')

for r in rng.rows:
print(r.address)
autofit()

Autofits the height of the rows.

count

Returns the number of rows.

New in version 0.9.0.

RangeColumns
classxlwings.RangeColumns(rng)

Represents the columns of a range. Do not construct this class directly,


use  Range.columns  instead.

Example
import xlwings as xw

rng = xw.Range('A1:C4')

assert len(rng.columns) == 3 # or rng.columns.count

rng.columns[0].value = 'a'

assert rng.columns[2] == xw.Range('C1:C4')


assert rng.columns(2) == xw.Range('B1:B4')

for c in rng.columns:
print(c.address)
autofit()

Autofits the width of the columns.

count

Returns the number of columns.


New in version 0.9.0.

Shapes
classxlwings.main.Shapes(impl)
A collection of all  shape  objects on the specified sheet:

>>> import xlwings as xw


>>> xw.books['Book1'].sheets[0].shapes
Shapes([<Shape 'Oval 1' in <Sheet [Book1]Sheet1>>, <Shape 'Rectangle 1' in <Sheet
[Book1]Sheet1>>])
New in version 0.9.0.

api
Returns the native object ( pywin32  or  appscript  obj) of the engine being used.

count

Returns the number of objects in the collection.

Shape
classxlwings.Shape(*args, **options)
The shape object is a member of the  shapes  collection:

>>> import xlwings as xw


>>> sht = xw.books['Book1'].sheets[0]
>>> sht.shapes[0] # or sht.shapes['ShapeName']
<Shape 'Rectangle 1' in <Sheet [Book1]Sheet1>>

Changed in version 0.9.0.

activate()

Activates the shape.

New in version 0.5.0.

api
Returns the native object ( pywin32  or  appscript  obj) of the engine being used.

New in version 0.19.2.

delete()

Deletes the shape.


New in version 0.5.0.

height

Returns or sets the number of points that represent the height of the shape.

New in version 0.5.0.

left

Returns or sets the number of points that represent the horizontal position of the
shape.

New in version 0.5.0.

name

Returns or sets the name of the shape.

New in version 0.5.0.

parent

Returns the parent of the shape.

New in version 0.9.0.

scale_height(factor, relative_to_original_size=False, scale='scale_from_top_left')
factor :float

For example 1.5 to scale it up to 150%

relative_to_original_size :bool, optional
If  False , it scales relative to current height (default). For  True  must be a picture or OLE
object.

scale :str, optional
One of  scale_from_top_left  (default),  scale_from_bottom_right ,  scale_from_middle

New in version 0.19.2.

scale_width(factor, relative_to_original_size=False, scale='scale_from_top_left')
factor :float

For example 1.5 to scale it up to 150%


relative_to_original_size :bool, optional
If  False , it scales relative to current width (default). For  True  must be a picture or OLE
object.

scale :str, optional
One of  scale_from_top_left  (default),  scale_from_bottom_right ,  scale_from_middle

New in version 0.19.2.

top

Returns or sets the number of points that represent the vertical position of the
shape.

New in version 0.5.0.

type

Returns the type of the shape.

New in version 0.9.0.

width

Returns or sets the number of points that represent the width of the shape.

New in version 0.5.0.

Charts
classxlwings.main.Charts(impl)
A collection of all  chart  objects on the specified sheet:

>>> import xlwings as xw


>>> xw.books['Book1'].sheets[0].charts
Charts([<Chart 'Chart 1' in <Sheet [Book1]Sheet1>>, <Chart 'Chart 1' in <Sheet
[Book1]Sheet1>>])
New in version 0.9.0.

add(left=0, top=0, width=355, height=211)

Creates a new chart on the specified sheet.

Parameters:  left (float,  default 0) – left position in


points
 top (float,  default 0) – top position in
points
 width (float,  default 355) – width in points
 height (float,  default 211) – height in
points

Returns:

Return
type: Chart

Examples
>>> import xlwings as xw
>>> sht = xw.Book().sheets[0]
>>> sht.range('A1').value = [['Foo1', 'Foo2'], [1, 2]]
>>> chart = sht.charts.add()
>>> chart.set_source_data(sht.range('A1').expand())
>>> chart.chart_type = 'line'
>>> chart.name
'Chart1'
api
Returns the native object ( pywin32  or  appscript  obj) of the engine being used.

count

Returns the number of objects in the collection.

Chart
classxlwings.Chart(name_or_index=None, impl=None)
The chart object is a member of the  charts  collection:

>>> import xlwings as xw


>>> sht = xw.books['Book1'].sheets[0]
>>> sht.charts[0] # or sht.charts['ChartName']
<Chart 'Chart 1' in <Sheet [Book1]Sheet1>>
api
Returns the native object ( pywin32  or  appscript  obj) of the engine being used.

New in version 0.9.0.

chart_type
Returns and sets the chart type of the chart.

New in version 0.1.1.

delete()

Deletes the chart.

height

Returns or sets the number of points that represent the height of the chart.

left

Returns or sets the number of points that represent the horizontal position of the
chart.

name

Returns or sets the name of the chart.

parent

Returns the parent of the chart.

New in version 0.9.0.

set_source_data(source)

Sets the source data range for the chart.

Parameters source (Range) – Range object,


: e.g.  xw.books['Book1'].sheets[0].range('A1')

top

Returns or sets the number of points that represent the vertical position of the
chart.

width

Returns or sets the number of points that represent the width of the chart.

Pictures
classxlwings.main.Pictures(impl)
A collection of all  picture  objects on the specified sheet:

>>> import xlwings as xw


>>> xw.books['Book1'].sheets[0].pictures
Pictures([<Picture 'Picture 1' in <Sheet [Book1]Sheet1>>, <Picture 'Picture 2' in
<Sheet [Book1]Sheet1>>])

New in version 0.9.0.

add(image, link_to_file=False, save_with_document=True, left=0, top=0, width=None, heigh
t=None, name=None, update=False, scale=1)

Adds a picture to the specified sheet.

 image (str  or  path-like object  or  matplotlib.figure.Figure) –


Either a filepath or a Matplotlib figure object.
 left (float,  default 0) – Left position in points.
 top (float,  default 0) – Top position in points.
 width (float,  default None) – Width in points. If PIL/Pillow is
installed, it defaults to the width of the picture. Otherwise it
defaults to 100 points.
Parameters:
 height (float,  default None) – Height in points. If PIL/Pillow is
installed, it defaults to the height of the picture. Otherwise it
defaults to 100 points.
 name (str,  default None) – Excel picture name. Defaults to
Excel standard name if not provided, e.g. ‘Picture 1’.
 update (bool,  default False) – Replace an existing picture with
the same name. Requires  name  to be set.

Returns:

Return
type: Picture

Examples

1. Picture

>>> import xlwings as xw


>>> sht = xw.Book().sheets[0]
>>> sht.pictures.add(r'C:\path\to\file.jpg')
<Picture 'Picture 1' in <Sheet [Book1]Sheet1>>
2. Matplotlib

>>> import matplotlib.pyplot as plt


>>> fig = plt.figure()
>>> plt.plot([1, 2, 3, 4, 5])
>>> sht.pictures.add(fig, name='MyPlot', update=True)
<Picture 'MyPlot' in <Sheet [Book1]Sheet1>>
api
Returns the native object ( pywin32  or  appscript  obj) of the engine being used.

count

Returns the number of objects in the collection.

Picture
classxlwings.Picture(impl=None)
The picture object is a member of the  pictures  collection:

>>> import xlwings as xw


>>> sht = xw.books['Book1'].sheets[0]
>>> sht.pictures[0] # or sht.charts['PictureName']
<Picture 'Picture 1' in <Sheet [Book1]Sheet1>>

Changed in version 0.9.0.

api
Returns the native object ( pywin32  or  appscript  obj) of the engine being used.

New in version 0.9.0.

delete()

Deletes the picture.

New in version 0.5.0.

height

Returns or sets the number of points that represent the height of the picture.

New in version 0.5.0.

left

Returns or sets the number of points that represent the horizontal position of the
picture.
New in version 0.5.0.

name

Returns or sets the name of the picture.

New in version 0.5.0.

parent

Returns the parent of the picture.

New in version 0.9.0.

top

Returns or sets the number of points that represent the vertical position of the
picture.

New in version 0.5.0.

update(image)

Replaces an existing picture with a new one, taking over the attributes of the
existing picture.

Parameters image (str  or  path-like object  or  matplotlib.figure.Figure) – Either a


: filepath or a Matplotlib figure object.

New in version 0.5.0.

width

Returns or sets the number of points that represent the width of the picture.

New in version 0.5.0.

Names
classxlwings.main.Names(impl)
A collection of all  name  objects in the workbook:

>>> import xlwings as xw


>>> sht = xw.books['Book1'].sheets[0]
>>> sht.names
[<Name 'MyName': =Sheet1!$A$3>]
New in version 0.9.0.

add(name, refers_to)

Defines a new name for a range of cells.

 name (str) – Specifies the text to use as the name. Names


cannot include spaces and cannot be formatted as cell
Parameters: references.
 refers_to (str) – Describes what the name refers to, in
English, using A1-style notation.

Returns:

Return
type: Name

New in version 0.9.0.

api
Returns the native object ( pywin32  or  appscript  obj) of the engine being used.

New in version 0.9.0.

count

Returns the number of objects in the collection.

Name
classxlwings.Name(impl)
The name object is a member of the  names  collection:

>>> import xlwings as xw


>>> sht = xw.books['Book1'].sheets[0]
>>> sht.names[0] # or sht.names['MyName']
<Name 'MyName': =Sheet1!$A$3>

New in version 0.9.0.

api
Returns the native object ( pywin32  or  appscript  obj) of the engine being used.
New in version 0.9.0.

delete()

Deletes the name.

New in version 0.9.0.

name

Returns or sets the name of the name object.

New in version 0.9.0.

refers_to

Returns or sets the formula that the name is defined to refer to, in A1-style
notation, beginning with an equal sign.

New in version 0.9.0.

refers_to_range

Returns the Range object referred to by a Name object.

New in version 0.9.0.

UDF decorators

xlwings.func(category="xlwings", volatile=False, call_in_wizard=True)
Functions decorated with  xlwings.func  will be imported as  Function  to Excel when
running “Import Python UDFs”.

category :int or str, default “xlwings”

1-14 represent built-in categories, for user-defined categories use strings

New in version 0.10.3.

volatile :bool, default False

Marks a user-defined function as volatile. A volatile function must be recalculated


whenever calculation occurs in any cells on the worksheet. A nonvolatile function
is recalculated only when the input variables change. This method has no effect if
it’s not inside a user-defined function used to calculate a worksheet cell.

New in version 0.10.3.

call_in_wizard :bool, default True

Set to False to suppress the function call in the function wizard.

New in version 0.10.3.

xlwings.sub()
Functions decorated with  xlwings.sub  will be imported as  Sub  (i.e. macro) to Excel
when running “Import Python UDFs”.

xlwings.arg(arg, convert=None, **options)
Apply converters and options to arguments, see also  Range.options() .

Examples:

Convert  x  into a 2-dimensional numpy array:

import xlwings as xw
import numpy as np

@xw.func
@xw.arg('x', np.array, ndim=2)
def add_one(x):
return x + 1

xlwings.ret(convert=None, **options)
Apply converters and options to return values, see also  Range.options() .

Examples

1. Suppress the index and header of a returned DataFrame:

import pandas as pd

@xw.func
@xw.ret(index=False, header=False)
def get_dataframe(n, m):
return pd.DataFrame(np.arange(n * m).reshape((n, m)))
2. Dynamic array:

Note

If your version of Excel supports the new native dynamic arrays, then you don’t
have to do anything special, and you shouldn’t use the  expand  decorator! To check
if your version of Excel supports it, see if you have the  =UNIQUE()  formula
available. Native dynamic arrays were introduced in Office 365 Insider Fast at the
end of September 2018.
expand='table'  turns the UDF into a dynamic array. Currently you must not use

volatile functions as arguments of a dynamic array, e.g. you cannot


use  =TODAY()  as part of a dynamic array. Also note that a dynamic array needs an
empty row and column at the bottom and to the right and will overwrite existing
data without warning.

Unlike standard Excel arrays, dynamic arrays are being used from a single cell like
a standard function and auto-expand depending on the dimensions of the
returned array:

import xlwings as xw
import numpy as np

@xw.func
@xw.ret(expand='table')
def dynamic_array(n, m):
return np.arange(n * m).reshape((n, m))
New in version 0.10.0.

Reports

xlwings.pro.reports.create_report(template, output, book_settings=None, app=None, **dat
a)
This feature requires xlwings  PRO .
Writes the values of all key word arguments to the  output  file according to
the  template  and the variables contained in there (Jinja variable syntax). Following
variable types are supported:

strings, numbers, lists, simple dicts, NumPy arrays, Pandas DataFrames, PIL Image
objects that have a filename and Matplotlib figures.
 template (str) – Path to your Excel template,
e.g.  r'C:\Path\to\my_template.xlsx'
 output (str) – Path to your Report,
e.g.  r'C:\Path\to\my_report.xlsx'
 book_settings (dict,  default None) – A dictionary
of  xlwings.Book  parameters, for details see:  xlwings.Book . For
example:  book_settings={'update_links': False} .
Parameters:
 app (xlwings App,  default None) – By passing in an xlwings
App instance, you can control where your report runs and
configure things like  visible=False . For details
see  xlwings.App . By default, it creates the report in the
currently active instance of Excel.
 data (kwargs) – All key/value pairs that are used in the
template.

Returns: wb

Return
type: xlwings Book

Examples

In  my_template.xlsx , put the following Jinja variables in two


cells:  {{ title }}  and  {{ df }}

>>> from xlwings.pro.reports import create_report


>>> import pandas as pd
>>> df = pd.DataFrame(data=[[1,2],[3,4]])
>>> wb = create_report('my_template.xlsx', 'my_report.xlsx', title='MyTitle', df=df)

With many template variables it may be useful to collect the data first:

>>> data = dict(title='MyTitle', df=df)


>>> wb = create_report('my_template.xlsx', 'my_report.xlsx', **data)

If you need to handle external links or a password, use it like so:

>>> wb = create_report('my_template.xlsx', 'my_report.xlsx',


book_settings={'update_links': True, 'password': 'mypassword'},
**data)
You can control the Excel instance by passing in an xlwings App instance. For
example, to run the report in a separate and hidden instance of Excel, do the
following:
>>> import xlwings as xw
>>> from xlwings.pro.reports import create_report
>>> app = xw.App(visible=False) # Separate and hidden Excel instance
>>> wb = create_report('my_template.xlsx', 'my_report.xlsx', app=app, **data)
>>> app.quit() # Close the wb and quit the Excel instance

REST API
New in version 0.13.0.

Quickstart
xlwings offers an easy way to expose an Excel workbook via REST API both on Windows
and macOS. This can be useful when you have a workbook running on a single computer
and want to access it from another computer. Or you can build a Linux based web app
that can interact with a legacy Excel application while you are in the progress of
migrating the Excel functionality into your web app (if you need help with that, give us a
shout).

You can run the REST API server from a command prompt or terminal as follows (this
requires Flask>=1.0, so make sure to  pip install Flask ):

xlwings restapi run


Then perform a GET request e.g. via PowerShell on Windows or Terminal on Mac (while
having an unsaved “Book1” open). Note that you need to run the server and the GET
request from two separate terminals (or you can use something more convenient
like Postman or Insomnia for testing the API):

$ curl "http://127.0.0.1:5000/book/book1/sheets/0/range/A1:B2"
{
"address": "$A$1:$B$2",
"color": null,
"column": 1,
"column_width": 10.0,
"count": 4,
"current_region": "$A$1:$B$2",
"formula": [
[
"1",
"2"
],
[
"3",
"4"
]
],
"formula_array": null,
"height": 32.0,
"last_cell": "$B$2",
"left": 0.0,
"name": null,
"number_format": "General",
"row": 1,
"row_height": 16.0,
"shape": [
2,
2
],
"size": 4,
"top": 0.0,
"value": [
[
1.0,
2.0
],
[
3.0,
4.0
]
],
"width": 130.0
}
In the command prompt where your server is running, press  Ctrl-C  to shut it down
again.

The xlwings REST API is a thin wrapper around the Python API which makes it very easy
if you have worked previously with xlwings. It also means that the REST API does
require the Excel application to be up and running which makes it a great choice if the
data in your Excel workbook is constantly changing as the REST API will always deliver
the current state of the workbook without the need of saving it first.

Note

Currently, we only provide the GET methods to read the workbook. If you are also
interested in the POST methods to edit the workbook, let us know via GitHub issues.
Some other things will also need improvement, most notably exception handling.
Run the server
xlwings  restapi run  will run a Flask development server on http://127.0.0.1:5000. You
can provide  --host  and  --port  as command line args and it also respects the Flask
environment variables like  FLASK_ENV=development .
If you want to have more control, you can run the server directly with Flask, see
the Flask docs for more details:

set FLASK_APP=xlwings.rest.api
flask run
If you are on Mac, use  export FLASK_APP=xlwings.rest.api  instead
of  set FLASK_APP=xlwings.rest.api .

For production, you can use any WSGI HTTP Server like gunicorn (on Mac)
or waitress (on Mac/Windows) to serve the API. For example, with gunicorn you would
do:  gunicorn xlwings.rest.api:api . Or with waitress (adjust the host accordingly if you
want to make the api accessible from outside of localhost):

from xlwings.rest.api import api


from waitress import serve
serve(wsgiapp, host='127.0.0.1', port=5000)

Indexing
While the Python API offers Python’s 0-based indexing (e.g.  xw.books[0] ) as well as
Excel’s 1-based indexing (e.g.  xw.books(1) ), the REST API only offers 0-based indexing,
e.g.  /books/0 .

Range Options
The REST API accepts Range options as query parameters,
see  xlwings.Range.options()  e.g.

/book/book1/sheets/0/range/A1?expand=table&transpose=true

Remember that  options  only affect the  value  property.

Endpoint overview

Endpoi Correspond
Short Description
nt s to

/book Book Finds your workbook across all open instances of Excel and will open
Endpoi Correspond
Short Description
nt s to

it if it can’t find it

/books Books Books collection of the active Excel instance

/apps Apps This allows you to specify the Excel instance you want to work with

Endpoint details
/book
GET /book/<fullname_or_name>

Example response:

{
"app": 1104,
"fullname": "C:\\Users\\felix\\DEV\\xlwings\\scripts\\Book1.xlsx",
"name": "Book1.xlsx",
"names": [
"Sheet1!myname1",
"myname2"
],
"selection": "Sheet2!$A$1",
"sheets": [
"Sheet1",
"Sheet2"
]
}

GET /book/<fullname_or_name>/names

Example response:

{
"names": [
{
"name": "Sheet1!myname1",
"refers_to": "=Sheet1!$B$2:$C$3"
},
{
"name": "myname2",
"refers_to": "=Sheet1!$A$1"
}
]
}

GET /book/<fullname_or_name>/names/<name>

Example response:
{
"name": "myname2",
"refers_to": "=Sheet1!$A$1"
}

GET /book/<fullname_or_name>/names/<name>/range

Example response:

{
"address": "$A$1",
"color": null,
"column": 1,
"column_width": 8.47,
"count": 1,
"current_region": "$A$1:$B$2",
"formula": "=1+1.1",
"formula_array": "=1+1,1",
"height": 14.25,
"last_cell": "$A$1",
"left": 0.0,
"name": "myname2",
"number_format": "General",
"row": 1,
"row_height": 14.3,
"shape": [
1,
1
],
"size": 1,
"top": 0.0,
"value": 2.1,
"width": 51.0
}

GET /book/<fullname_or_name>/sheets

Example response:

{
"sheets": [
{
"charts": [
"Chart 1"
],
"name": "Sheet1",
"names": [
"Sheet1!myname1"
],
"pictures": [
"Picture 3"
],
"shapes": [
"Chart 1",
"Picture 3"
],
"used_range": "$A$1:$B$2"
},
{
"charts": [],
"name": "Sheet2",
"names": [],
"pictures": [],
"shapes": [],
"used_range": "$A$1"
}
]
}

GET /book/<fullname_or_name>/sheets/<sheet_name_or_ix>

Example response:

{
"charts": [
"Chart 1"
],
"name": "Sheet1",
"names": [
"Sheet1!myname1"
],
"pictures": [
"Picture 3"
],
"shapes": [
"Chart 1",
"Picture 3"
],
"used_range": "$A$1:$B$2"
}

GET /book/<fullname_or_name>/sheets/<sheet_name_or_ix>/charts

Example response:

{
"charts": [
{
"chart_type": "line",
"height": 211.0,
"left": 0.0,
"name": "Chart 1",
"top": 0.0,
"width": 355.0
}
]
}

GET /book/<fullname_or_name>/sheets/<sheet_name_or_ix>/charts/<chart_name_or_ix>

Example response:

{
"chart_type": "line",
"height": 211.0,
"left": 0.0,
"name": "Chart 1",
"top": 0.0,
"width": 355.0
}

GET /book/<fullname_or_name>/sheets/<sheet_name_or_ix>/names

Example response:

{
"names": [
{
"name": "Sheet1!myname1",
"refers_to": "=Sheet1!$B$2:$C$3"
}
]
}

GET /book/<fullname_or_name>/sheets/<sheet_name_or_ix>/names/<sheet_scope_name>

Example response:

{
"name": "Sheet1!myname1",
"refers_to": "=Sheet1!$B$2:$C$3"
}

GET /book/<fullname_or_name>/sheets/<sheet_name_or_ix>/names/<sheet_scope_name>/range

Example response:

{
"address": "$B$2:$C$3",
"color": null,
"column": 2,
"column_width": 8.47,
"count": 4,
"current_region": "$A$1:$B$2",
"formula": [
[
"",
""
],
[
"",
""
]
],
"formula_array": "",
"height": 28.5,
"last_cell": "$C$3",
"left": 51.0,
"name": "Sheet1!myname1",
"number_format": "General",
"row": 2,
"row_height": 14.3,
"shape": [
2,
2
],
"size": 4,
"top": 14.25,
"value": [
[
null,
null
],
[
null,
null
]
],
"width": 102.0
}

GET /book/<fullname_or_name>/sheets/<sheet_name_or_ix>/pictures

Example response:

{
"pictures": [
{
"height": 100.0,
"left": 0.0,
"name": "Picture 3",
"top": 0.0,
"width": 100.0
}
]
}

GET /book/<fullname_or_name>/sheets/<sheet_name_or_ix>/pictures/<picture_name_or_ix>

Example response:

{
"height": 100.0,
"left": 0.0,
"name": "Picture 3",
"top": 0.0,
"width": 100.0
}

GET /book/<fullname_or_name>/sheets/<sheet_name_or_ix>/range

Example response:

{
"address": "$A$1:$B$2",
"color": null,
"column": 1,
"column_width": 8.47,
"count": 4,
"current_region": "$A$1:$B$2",
"formula": [
[
"=1+1.1",
"a string"
],
[
"43395.0064583333",
""
]
],
"formula_array": null,
"height": 28.5,
"last_cell": "$B$2",
"left": 0.0,
"name": null,
"number_format": null,
"row": 1,
"row_height": 14.3,
"shape": [
2,
2
],
"size": 4,
"top": 0.0,
"value": [
[
2.1,
"a string"
],
[
"Mon, 22 Oct 2018 00:09:18 GMT",
null
]
],
"width": 102.0
}

GET /book/<fullname_or_name>/sheets/<sheet_name_or_ix>/range/<address>

Example response:

{
"address": "$A$1:$B$2",
"color": null,
"column": 1,
"column_width": 8.47,
"count": 4,
"current_region": "$A$1:$B$2",
"formula": [
[
"=1+1.1",
"a string"
],
[
"43395.0064583333",
""
]
],
"formula_array": null,
"height": 28.5,
"last_cell": "$B$2",
"left": 0.0,
"name": null,
"number_format": null,
"row": 1,
"row_height": 14.3,
"shape": [
2,
2
],
"size": 4,
"top": 0.0,
"value": [
[
2.1,
"a string"
],
[
"Mon, 22 Oct 2018 00:09:18 GMT",
null
]
],
"width": 102.0
}

GET /book/<fullname_or_name>/sheets/<sheet_name_or_ix>/shapes

Example response:

{
"shapes": [
{
"height": 211.0,
"left": 0.0,
"name": "Chart 1",
"top": 0.0,
"type": "chart",
"width": 355.0
},
{
"height": 100.0,
"left": 0.0,
"name": "Picture 3",
"top": 0.0,
"type": "picture",
"width": 100.0
}
]
}

GET /book/<fullname_or_name>/sheets/<sheet_name_or_ix>/shapes/<shape_name_or_ix>

Example response:

{
"height": 211.0,
"left": 0.0,
"name": "Chart 1",
"top": 0.0,
"type": "chart",
"width": 355.0
}
/books
GET /books
Example response:

{
"books": [
{
"app": 1104,
"fullname": "Book1",
"name": "Book1",
"names": [],
"selection": "Sheet2!$A$1",
"sheets": [
"Sheet1"
]
},
{
"app": 1104,
"fullname": "C:\\Users\\felix\\DEV\\xlwings\\scripts\\Book1.xlsx",
"name": "Book1.xlsx",
"names": [
"Sheet1!myname1",
"myname2"
],
"selection": "Sheet2!$A$1",
"sheets": [
"Sheet1",
"Sheet2"
]
},
{
"app": 1104,
"fullname": "Book4",
"name": "Book4",
"names": [],
"selection": "Sheet2!$A$1",
"sheets": [
"Sheet1"
]
}
]
}

GET /books/<book_name_or_ix>

Example response:

{
"app": 1104,
"fullname": "C:\\Users\\felix\\DEV\\xlwings\\scripts\\Book1.xlsx",
"name": "Book1.xlsx",
"names": [
"Sheet1!myname1",
"myname2"
],
"selection": "Sheet2!$A$1",
"sheets": [
"Sheet1",
"Sheet2"
]
}
GET /books/<book_name_or_ix>/names

Example response:

{
"names": [
{
"name": "Sheet1!myname1",
"refers_to": "=Sheet1!$B$2:$C$3"
},
{
"name": "myname2",
"refers_to": "=Sheet1!$A$1"
}
]
}

GET /books/<book_name_or_ix>/names/<name>

Example response:

{
"name": "myname2",
"refers_to": "=Sheet1!$A$1"
}

GET /books/<book_name_or_ix>/names/<name>/range

Example response:

{
"address": "$A$1",
"color": null,
"column": 1,
"column_width": 8.47,
"count": 1,
"current_region": "$A$1:$B$2",
"formula": "=1+1.1",
"formula_array": "=1+1,1",
"height": 14.25,
"last_cell": "$A$1",
"left": 0.0,
"name": "myname2",
"number_format": "General",
"row": 1,
"row_height": 14.3,
"shape": [
1,
1
],
"size": 1,
"top": 0.0,
"value": 2.1,
"width": 51.0
}

GET /books/<book_name_or_ix>/sheets
Example response:

{
"sheets": [
{
"charts": [
"Chart 1"
],
"name": "Sheet1",
"names": [
"Sheet1!myname1"
],
"pictures": [
"Picture 3"
],
"shapes": [
"Chart 1",
"Picture 3"
],
"used_range": "$A$1:$B$2"
},
{
"charts": [],
"name": "Sheet2",
"names": [],
"pictures": [],
"shapes": [],
"used_range": "$A$1"
}
]
}

GET /books/<book_name_or_ix>/sheets/<sheet_name_or_ix>

Example response:

{
"charts": [
"Chart 1"
],
"name": "Sheet1",
"names": [
"Sheet1!myname1"
],
"pictures": [
"Picture 3"
],
"shapes": [
"Chart 1",
"Picture 3"
],
"used_range": "$A$1:$B$2"
}

GET /books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/charts

Example response:
{
"charts": [
{
"chart_type": "line",
"height": 211.0,
"left": 0.0,
"name": "Chart 1",
"top": 0.0,
"width": 355.0
}
]
}

GET /books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/charts/<chart_name_or_ix>

Example response:

{
"chart_type": "line",
"height": 211.0,
"left": 0.0,
"name": "Chart 1",
"top": 0.0,
"width": 355.0
}

GET /books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/names

Example response:

{
"names": [
{
"name": "Sheet1!myname1",
"refers_to": "=Sheet1!$B$2:$C$3"
}
]
}

GET /books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/names/<sheet_scope_name>

Example response:

{
"name": "Sheet1!myname1",
"refers_to": "=Sheet1!$B$2:$C$3"
}

GET /books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/names/<sheet_scope_name>/range

Example response:

{
"address": "$B$2:$C$3",
"color": null,
"column": 2,
"column_width": 8.47,
"count": 4,
"current_region": "$A$1:$B$2",
"formula": [
[
"",
""
],
[
"",
""
]
],
"formula_array": "",
"height": 28.5,
"last_cell": "$C$3",
"left": 51.0,
"name": "Sheet1!myname1",
"number_format": "General",
"row": 2,
"row_height": 14.3,
"shape": [
2,
2
],
"size": 4,
"top": 14.25,
"value": [
[
null,
null
],
[
null,
null
]
],
"width": 102.0
}

GET /books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/pictures

Example response:

{
"pictures": [
{
"height": 100.0,
"left": 0.0,
"name": "Picture 3",
"top": 0.0,
"width": 100.0
}
]
}

GET /books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/pictures/<picture_name_or_ix>

Example response:

{
"height": 100.0,
"left": 0.0,
"name": "Picture 3",
"top": 0.0,
"width": 100.0
}

GET /books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/range

Example response:

{
"address": "$A$1:$B$2",
"color": null,
"column": 1,
"column_width": 8.47,
"count": 4,
"current_region": "$A$1:$B$2",
"formula": [
[
"=1+1.1",
"a string"
],
[
"43395.0064583333",
""
]
],
"formula_array": null,
"height": 28.5,
"last_cell": "$B$2",
"left": 0.0,
"name": null,
"number_format": null,
"row": 1,
"row_height": 14.3,
"shape": [
2,
2
],
"size": 4,
"top": 0.0,
"value": [
[
2.1,
"a string"
],
[
"Mon, 22 Oct 2018 00:09:18 GMT",
null
]
],
"width": 102.0
}

GET /books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/range/<address>

Example response:
{
"address": "$A$1:$B$2",
"color": null,
"column": 1,
"column_width": 8.47,
"count": 4,
"current_region": "$A$1:$B$2",
"formula": [
[
"=1+1.1",
"a string"
],
[
"43395.0064583333",
""
]
],
"formula_array": null,
"height": 28.5,
"last_cell": "$B$2",
"left": 0.0,
"name": null,
"number_format": null,
"row": 1,
"row_height": 14.3,
"shape": [
2,
2
],
"size": 4,
"top": 0.0,
"value": [
[
2.1,
"a string"
],
[
"Mon, 22 Oct 2018 00:09:18 GMT",
null
]
],
"width": 102.0
}

GET /books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/shapes

Example response:

{
"shapes": [
{
"height": 211.0,
"left": 0.0,
"name": "Chart 1",
"top": 0.0,
"type": "chart",
"width": 355.0
},
{
"height": 100.0,
"left": 0.0,
"name": "Picture 3",
"top": 0.0,
"type": "picture",
"width": 100.0
}
]
}

GET /books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/shapes/<shape_name_or_ix>

Example response:

{
"height": 211.0,
"left": 0.0,
"name": "Chart 1",
"top": 0.0,
"type": "chart",
"width": 355.0
}
/apps
GET /apps

Example response:

{
"apps": [
{
"books": [
"Book1",
"C:\\Users\\felix\\DEV\\xlwings\\scripts\\Book1.xlsx",
"Book4"
],
"calculation": "automatic",
"display_alerts": true,
"pid": 1104,
"screen_updating": true,
"selection": "[Book1.xlsx]Sheet2!$A$1",
"version": "16.0",
"visible": true
},
{
"books": [
"Book2",
"Book5"
],
"calculation": "automatic",
"display_alerts": true,
"pid": 7920,
"screen_updating": true,
"selection": "[Book5]Sheet2!$A$1",
"version": "16.0",
"visible": true
}
]
}
GET /apps/<pid>

Example response:

{
"books": [
"Book1",
"C:\\Users\\felix\\DEV\\xlwings\\scripts\\Book1.xlsx",
"Book4"
],
"calculation": "automatic",
"display_alerts": true,
"pid": 1104,
"screen_updating": true,
"selection": "[Book1.xlsx]Sheet2!$A$1",
"version": "16.0",
"visible": true
}

GET /apps/<pid>/books

Example response:

{
"books": [
{
"app": 1104,
"fullname": "Book1",
"name": "Book1",
"names": [],
"selection": "Sheet2!$A$1",
"sheets": [
"Sheet1"
]
},
{
"app": 1104,
"fullname": "C:\\Users\\felix\\DEV\\xlwings\\scripts\\Book1.xlsx",
"name": "Book1.xlsx",
"names": [
"Sheet1!myname1",
"myname2"
],
"selection": "Sheet2!$A$1",
"sheets": [
"Sheet1",
"Sheet2"
]
},
{
"app": 1104,
"fullname": "Book4",
"name": "Book4",
"names": [],
"selection": "Sheet2!$A$1",
"sheets": [
"Sheet1"
]
}
]
}

GET /apps/<pid>/books/<book_name_or_ix>

Example response:

{
"app": 1104,
"fullname": "C:\\Users\\felix\\DEV\\xlwings\\scripts\\Book1.xlsx",
"name": "Book1.xlsx",
"names": [
"Sheet1!myname1",
"myname2"
],
"selection": "Sheet2!$A$1",
"sheets": [
"Sheet1",
"Sheet2"
]
}

GET /apps/<pid>/books/<book_name_or_ix>/names

Example response:

{
"names": [
{
"name": "Sheet1!myname1",
"refers_to": "=Sheet1!$B$2:$C$3"
},
{
"name": "myname2",
"refers_to": "=Sheet1!$A$1"
}
]
}

GET /apps/<pid>/books/<book_name_or_ix>/names/<name>

Example response:

{
"name": "myname2",
"refers_to": "=Sheet1!$A$1"
}

GET /apps/<pid>/books/<book_name_or_ix>/names/<name>/range

Example response:

{
"address": "$A$1",
"color": null,
"column": 1,
"column_width": 8.47,
"count": 1,
"current_region": "$A$1:$B$2",
"formula": "=1+1.1",
"formula_array": "=1+1,1",
"height": 14.25,
"last_cell": "$A$1",
"left": 0.0,
"name": "myname2",
"number_format": "General",
"row": 1,
"row_height": 14.3,
"shape": [
1,
1
],
"size": 1,
"top": 0.0,
"value": 2.1,
"width": 51.0
}

GET /apps/<pid>/books/<book_name_or_ix>/sheets

Example response:

{
"sheets": [
{
"charts": [
"Chart 1"
],
"name": "Sheet1",
"names": [
"Sheet1!myname1"
],
"pictures": [
"Picture 3"
],
"shapes": [
"Chart 1",
"Picture 3"
],
"used_range": "$A$1:$B$2"
},
{
"charts": [],
"name": "Sheet2",
"names": [],
"pictures": [],
"shapes": [],
"used_range": "$A$1"
}
]
}

GET /apps/<pid>/books/<book_name_or_ix>/sheets/<sheet_name_or_ix>

Example response:
{
"charts": [
"Chart 1"
],
"name": "Sheet1",
"names": [
"Sheet1!myname1"
],
"pictures": [
"Picture 3"
],
"shapes": [
"Chart 1",
"Picture 3"
],
"used_range": "$A$1:$B$2"
}

GET /apps/<pid>/books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/charts

Example response:

{
"charts": [
{
"chart_type": "line",
"height": 211.0,
"left": 0.0,
"name": "Chart 1",
"top": 0.0,
"width": 355.0
}
]
}

GET /apps/<pid>/books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/charts/<chart_name_
or_ix>

Example response:

{
"chart_type": "line",
"height": 211.0,
"left": 0.0,
"name": "Chart 1",
"top": 0.0,
"width": 355.0
}

GET /apps/<pid>/books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/names

Example response:

{
"names": [
{
"name": "Sheet1!myname1",
"refers_to": "=Sheet1!$B$2:$C$3"
}
]
}

GET /apps/<pid>/books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/names/<sheet_scope_
name>

Example response:

{
"name": "Sheet1!myname1",
"refers_to": "=Sheet1!$B$2:$C$3"
}

GET /apps/<pid>/books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/names/<sheet_scope_
name>/range

Example response:

{
"address": "$B$2:$C$3",
"color": null,
"column": 2,
"column_width": 8.47,
"count": 4,
"current_region": "$A$1:$B$2",
"formula": [
[
"",
""
],
[
"",
""
]
],
"formula_array": "",
"height": 28.5,
"last_cell": "$C$3",
"left": 51.0,
"name": "Sheet1!myname1",
"number_format": "General",
"row": 2,
"row_height": 14.3,
"shape": [
2,
2
],
"size": 4,
"top": 14.25,
"value": [
[
null,
null
],
[
null,
null
]
],
"width": 102.0
}

GET /apps/<pid>/books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/pictures

Example response:

{
"pictures": [
{
"height": 100.0,
"left": 0.0,
"name": "Picture 3",
"top": 0.0,
"width": 100.0
}
]
}

GET /apps/<pid>/books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/pictures/<picture_n
ame_or_ix>

Example response:

{
"height": 100.0,
"left": 0.0,
"name": "Picture 3",
"top": 0.0,
"width": 100.0
}

GET /apps/<pid>/books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/range

Example response:

{
"address": "$A$1:$B$2",
"color": null,
"column": 1,
"column_width": 8.47,
"count": 4,
"current_region": "$A$1:$B$2",
"formula": [
[
"=1+1.1",
"a string"
],
[
"43395.0064583333",
""
]
],
"formula_array": null,
"height": 28.5,
"last_cell": "$B$2",
"left": 0.0,
"name": null,
"number_format": null,
"row": 1,
"row_height": 14.3,
"shape": [
2,
2
],
"size": 4,
"top": 0.0,
"value": [
[
2.1,
"a string"
],
[
"Mon, 22 Oct 2018 00:09:18 GMT",
null
]
],
"width": 102.0
}

GET /apps/<pid>/books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/range/<address>

Example response:

{
"address": "$A$1:$B$2",
"color": null,
"column": 1,
"column_width": 8.47,
"count": 4,
"current_region": "$A$1:$B$2",
"formula": [
[
"=1+1.1",
"a string"
],
[
"43395.0064583333",
""
]
],
"formula_array": null,
"height": 28.5,
"last_cell": "$B$2",
"left": 0.0,
"name": null,
"number_format": null,
"row": 1,
"row_height": 14.3,
"shape": [
2,
2
],
"size": 4,
"top": 0.0,
"value": [
[
2.1,
"a string"
],
[
"Mon, 22 Oct 2018 00:09:18 GMT",
null
]
],
"width": 102.0
}

GET /apps/<pid>/books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/shapes

Example response:

{
"shapes": [
{
"height": 211.0,
"left": 0.0,
"name": "Chart 1",
"top": 0.0,
"type": "chart",
"width": 355.0
},
{
"height": 100.0,
"left": 0.0,
"name": "Picture 3",
"top": 0.0,
"type": "picture",
"width": 100.0
}
]
}

GET /apps/<pid>/books/<book_name_or_ix>/sheets/<sheet_name_or_ix>/shapes/<shape_name_
or_ix>

Example response:

{
"height": 211.0,
"left": 0.0,
"name": "Chart 1",
"top": 0.0,
"type": "chart",
"width": 355.0
}
 Previous

You might also like