Python Note Book

Download as pdf or txt
Download as pdf or txt
You are on page 1of 76

PYTHON FUNDAMENTALS

V SHANMUGANEETHI
ASSOCIATE PROFESSOR, DCSE, NITTTR CHENNAI
WHAT IS PYTHON

 Python is an interpreted,
 object-oriented,
 high-level programming language with dynamic semantics.

 Python is Interactive
 Sit at a Python prompt and interact with the interpreter directly to write your programs.

 Its high-level built in data structures, combined with


 dynamic typing and
 dynamic binding, make it very attractive for Rapid Application Development
FEATURES

 Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax. This allows
the learner to pick up the language quickly.
 Easy-to-read: Python code is more clearly defined
 Easy-to-maintain: Python's source code is fairly easy-to-maintain.
 A broad standard library: Python's bulk of the library is very portable and cross-platform
compatible on UNIX,Windows, and Macintosh.
 Interactive Mode: Python has support for an interactive mode which allows interactive testing and
debugging of snippets of code.
FEATURES

 Portable: Python can run on a wide variety of hardware platforms and has the same interface on all
platforms.
 Extendable: You can add low-level modules to the Python interpreter. These modules enable
programmers to add to or customize their tools to be more efficient.
 Databases: Python provides interfaces to all major commercial databases.
 GUI Programming: Python supports GUI applications that can be created and ported to many
system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window
system of Unix.
 Scalable: Python provides a better structure and support for large programs than shell scripting.
PYTHON IDENTIFIERS

 A Python identifier is a name used to identify a variable, function, class, module or


other object. An identifier starts with a letter A to Z or a to z or an underscore (_)
followed by zero or more letters, underscores and digits (0 to 9).
 Python does not allow punctuation characters such as @, $, and % within identifiers.
Python is a case sensitive programming language. Thus, Manpower
and manpower are two different identifiers in Python.
PYTHON IDENTIFIERS

 Here are naming conventions for Python identifiers −


 Class names start with an uppercase letter.All other identifiers start with a lowercase letter.
 Starting an identifier with a single leading underscore indicates that the identifier is private.
 Starting an identifier with two leading underscores indicates a strongly private identifier.
 If the identifier also ends with two trailing underscores, the identifier is a language-defined
special name.
RESERVED WORDS
And exec Not
Assert finally or
Break for pass
Class from print
Continue global raise
def if return
del import try
elif in while
else is with
except lambda yield
COMMENTS
DATA TYPES

 Python has many useful built-in data types. Python variables can store
different types of data based on a variable's data type. A variable's data
type is created dynamically, without the need to explicitly define a data
type when the variable is created.
STANDARD DATA TYPES – BUILT-IN DATATYPES

 Numbers
 Integer
 Floating point number
 Complex number
 String
 List
 Tuple
 Dictionary
NUMBER

 Number data types store numeric values. They are immutable data types, means that
changing the value of a number data type results in a newly allocated object.
var1 = 1
var2 = 10

 Number objects are created when you assign a value to them


del var
del var_a, var_b

 delete a single object or multiple objects by using the del statement


NUMERICAL TYPES

 Python supports four different numerical types −


 int (signed integers): They are often called just integers or ints, are positive or negative whole numbers with no
decimal point.
 long (long integers ): Also called longs, they are integers of unlimited size, written like integers and followed by an
uppercase or lowercase L.
 float (floating point real values) : Also called floats, they represent real numbers and are written with a decimal
point dividing the integer and fractional parts. Floats may also be in scientific notation, with E or e indicating the
power of 10 (2.5e2 = 2.5 x 102 = 250).
 complex (complex numbers) : are of the form a + bJ, where a and b are floats and J (or j) represents the square
root of -1 (which is an imaginary number). The real part of the number is a, and the imaginary part is b. Complex
numbers are not used much in Python programming.
NUMBER TYPE CONVERSION

 Type int(x) to convert x to a plain integer.


 Type long(x) to convert x to a long integer.
 Type float(x) to convert x to a floating-point number.
 Type complex(x) to convert x to a complex number with real part x and imaginary part zero.
 Type complex(x, y) to convert x and y to a complex number with real part x and imaginary part y. x
and y are numeric expressions
MATHEMATICAL FUNCTIONS
Function Returns ( description )
abs(x) The absolute value of x: the (positive) distance between x and zero.
ceil(x) The ceiling of x: the smallest integer not less than x
cmp(x, y) -1 if x < y, 0 if x == y, or 1 if x > y
x
exp(x) The exponential of x: e
fabs(x) The absolute value of x.
floor(x) The floor of x: the largest integer not greater than x
log(x) The natural logarithm of x, for x> 0
log10(x) The base-10 logarithm of x for x> 0 .
max(x1, x2,...) The largest of its arguments: the value closest to positive infinity
min(x1, x2,...) The smallest of its arguments: the value closest to negative infinity
modf(x) The fractional and integer parts of x in a two-item tuple. Both parts have the same sign as x. The integer part is returned as a float.

pow(x, y) The value of x**y.


round(x [,n]) x rounded to n digits from the decimal point. Python rounds away from zero as a tie-breaker: round(0.5) is 1.0 and round(-0.5) is -1.0.
sqrt(x) The square root of x for x > 0
RANDOM NUMBER FUNCTIONS
Function Description
choice(seq) A random item from a list, tuple, or string.
randrange ([start,] stop A randomly selected element from range(start, stop, step)
[,step])
random() A random float r, such that 0 is less than or equal to r and r is less than 1

seed([x]) Sets the integer starting value used in generating random numbers. Call this
function before calling any other random module function. Returns None.

shuffle(lst) Randomizes the items of a list in place. Returns None.


uniform(x, y) A random float r, such that x is less than or equal to r and r is less than y
DATA TYPES EXAMPLE

 print ('This program is a demo of variables')


 val_i = 20
 print (“Type of the variable:”, type(val_i))

 print ('This program is a demo of variables')


 val_f = 20.45
 print (“Type of the variable:”, type(val_f))
DATA TYPES EXAMPLE

 print ('This program is a demo of variables')


 val_c = 20 +4j
 print (“Type of the variable:”, type(val_c))
BOOLEAN TYPE

 The boolean data type is either True or False. In Python, boolean variables are defined by the True and
False keywords.
 a = True
 type(a)
 <class 'bool'>
 Integers and floating point numbers can be converted to the boolean data type using Python's bool()
function.
 An int, float or complex number set to zero returns False. An integer, float or complex number set to
any other number, positive or negative, returns True.
BOOL FUNCTION

 zero_int = 0
 bool(zero_int)
 False

 pos_int = 1
 bool(pos_int)
 True
TYPES OF OPERATOR

 Python language supports the following types of operators.


 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators
ARITHMETIC OPERATORS

Operator Description Example

+ Addition Adds values on either side of the operator. a + b = 30

- Subtraction Subtracts right hand operand from left hand operand. a – b = -10

* Multiplication Multiplies values on either side of the operator a * b = 200

/ Division Divides left hand operand by right hand operand b/a=2

Divides left hand operand by right hand operand and returns b%a=0
% Modulus
remainder
a**b =10 to the power 20
** Exponent Performs exponential (power) calculation on operators

Floor Division - The division of operands where the result is the 9//2 = 4 and 9.0//2.0 = 4.0
//
quotient in which the digits after the decimal point are removed.
COMPARISON OPERATORS
Operator Description Example
== If the values of two operands are equal, then the condition becomes true. (a == b) is not true.

!= If values of two operands are not equal, then condition becomes true.
<> If values of two operands are not equal, then condition becomes true. (a <> b) is true. This is similar
to != operator.
> If the value of left operand is greater than the value of right operand, then (a > b) is not true.
condition becomes true.
< If the value of left operand is less than the value of right operand, then (a < b) is true.
condition becomes true.
>= If the value of left operand is greater than or equal to the value of right (a >= b) is not true.
operand, then condition becomes true.
<= If the value of left operand is less than or equal to the value of right (a <= b) is true.
operand, then condition becomes true.
ASSIGNMENT OPERATORS
Operator Description Example
= Assigns values from right side operands to left side operand c = a + b assigns value of a + b into c
It adds right operand to the left operand and assign the result to left
+= Add AND c += a is equivalent to c = c + a
operand
It subtracts right operand from the left operand and assign the result to
-= Subtract AND c -= a is equivalent to c = c - a
left operand
It multiplies right operand with the left operand and assign the result to
*= Multiply AND c *= a is equivalent to c = c * a
left operand
It divides left operand with the right operand and assign the result to c /= a is equivalent to c = c / ac /= a is
/= Divide AND
left operand equivalent to c = c / a
It takes modulus using two operands and assign the result to left
%= Modulus AND c %= a is equivalent to c = c % a
operand
**= Exponent Performs exponential (power) calculation on operators and assign value
c **= a is equivalent to c = c ** a
AND to the left operand
It performs floor division on operators and assign value to the left
//= Floor Division c //= a is equivalent to c = c // a
operand
STRINGS

 Strings in Python are identified as a continuous set of characters


represented in the quotation marks. Python allows for either pairs of
single or double quotes. Subsets of strings can be taken using the slice
operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the
string and working their way from -1 at the end.
 The plus (+) sign is the string concatenation operator and the asterisk
(*) is the repetition operator.
STRING OPERATORS
Operator Description
+ It is known as concatenation operator used to join the strings given either side of the operator.
* It is known as repetition operator. It concatenates the multiple copies of the same string.
[] It is known as slice operator. It is used to access the sub-strings of a particular string.
[:] It is known as range slice operator. It is used to access the characters from the specified range.
in It is known as membership operator. It returns if a particular sub-string is present in the specified string.
It is also a membership operator and does the exact reverse of in. It returns true if a particular substring is
not in
not present in the specified string.
It is used to specify the raw string. Raw strings are used in the cases where we need to print the actual
r/R meaning of escape characters such as "C://python". To define any string as a raw string, the character r or R is
followed by the string.

It is used to perform string formatting. It makes use of the format specifiers used in C programming like %d
%
or %f to map their values in python.
INDEXING

 Like other languages, the indexing of the Python strings starts from 0. For example, The string "HELLO" is indexed as
given in the below figure.

s h a n n e e t h i
0 1 2 3 4 5 6 7 8 9
 str ='shannethi'
 print('str[0] = ',str[0])
 print('str[1] = ',str[1])
 str[0] = s
 str[1] = h
STRING OPERATIONS - SLICING

 valstr = 'Hello World!'


 print (valstr) # Prints complete string
 print (valstr[0]) # Prints first character of the string
 print(str[0:]) # Start 0th index to end
 print(str[:3]) # Starts 2nd index to 3rd index
 print (valstr[2:5]) # Prints characters starting from 3rd to 5th
 print (valstr[2:]) # Prints string starting from 3rd character
 print (valstr * 2) # Prints string two times
 print (valstr + 'TEST') # Prints concatenated string
DELETING A STRING

 del str
 print(str)
STRING METHODS

Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string

find() Searches the string for a specified value and returns the position of where it was found

format() Formats specified values in a string


STRING METHODS
Methods Description
format_map() Formats specified values in a string
index() Searches the string for a specified value and returns the position of where it was found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isascii() Returns True if all characters in the string are ascii characters
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
STRING METHODS
Methods Description
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Converts the elements of an iterable into a string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of where it was found
STRING METHODS
Methods Description
rindex() Searches the string for a specified value and returns the last position of where it was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
METHODS
Methods Description
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning
PYTHON LISTS

 Lists are the most versatile of Python's compound data types. A list contains items
separated by commas and enclosed within square brackets ([]).
 To some extent, lists are similar to arrays in C. One difference between them is that
all the items belonging to a list can be of different data type.
 The values stored in a list can be accessed using the slice operator ([ ] and [:]) with
indexes starting at 0 in the beginning of the list and working their way to end -1. The
plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition
operator.
LIST

mylist = [ 'abcd', 123 , 'shan', 'muga', 'neethi', 70.2 ]


tinylist = [123, 'shan', 'neethi']

print (mylist) # Prints complete list


print (mylist[0]) # Prints first element of the list
print (mylist[1:3]) # Prints elements starting from 2nd till 3rd
print (mylist[2:]) # Prints elements starting from 3rd element
print (tinylist * 2) # Prints list two times
print (mylist + tinylist) # Prints concatenated lists
TUPLES

 A tuple is another sequence data type that is similar to the list. A tuple
consists of a number of values separated by commas. Unlike lists,
however, tuples are enclosed within parentheses.
 The main differences between lists and tuples are: Lists are enclosed in
brackets ( [ ] ) and their elements and size can be changed, while tuples
are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be
thought of as read-only lists.
TUPLES

mytuple = ( 'abcd', 123 , 'shan', 'muga', 'neethi', 70.2 )


tinytuple = (123, 'shan', 'neethi')
print (mytuple) # Prints complete list
print (mytuple[0]) # Prints first element of the list
print (mytuple[1:3]) # Prints elements starting from 2nd till 3rd
print (mytuple[2:]) # Prints elements starting from 3rd element
print (tinytuple * 2) # Prints list two times
print (mytuple + tinytuple) # Prints concatenated lists
DICTIONARY

 Python's dictionaries are kind of hash table type. They work like associative arrays or
hashes found in Perl and consist of key-value pairs.
 A dictionary key can be almost any Python type, but are usually numbers or strings.
Values, on the other hand, can be any arbitrary Python object.
 Dictionaries are enclosed by curly braces ({ }) and values can be assigned and
accessed using square braces ([]).
DICTIONARY

d={
<key>: <value>,
<key>: <value>,
.
.
.
<key>: <value>
}
DICTIONARY

 dict = {}
 dict['one'] = "name of the user"
 dict[2] = "gender"
 dict[3] = "dept"
 dict[4] = "address"
 tinydict = {'name': 'shanmuganeethi.v','mobile':6734, 'dept': 'Computer Centre'}
 print (dict['one']) # Prints value for 'one' key
 print (dict[2]) # Prints value for 2 key
 print (dict[4]) # Prints value for 4 key
 print (tinydict) # Prints complete dictionary
 print (tinydict.keys()) # Prints all the keys
 print (tinydict.values()) # Prints all the values
IF STATEMENT

Statement Description
if statements An if statement consists of a boolean expression followed
by one or more statements.

if...else statements An if statement can be followed by an optional else


statement, which executes when the boolean expression
is FALSE.

nested if statements You can use one if or else if statement inside


another if or else if statement(s).
DECISION STATEMENTS
IF STATEMENT

if expression:
statement(s)
IF STATEMENT

print('shanmuganeethi.v')
inputval=int(input('Enter the Number'));
if(inputval == 25) :
print("Enter the value is correct")
print("if statement working , Good bye")
IF .. ELSE

if expression:
statement(s)
else:
statement(s)
IF .. ELSE

strval = input("Enter your city")


if(strval=='chennai'):
print("Your city is in south")
print("Your city is safe")
else:
print("your city is not at south")
print("your city is not safe")
print("if else is working")
NESTED STATEMENTS

if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
else statement(s)
elif expression4:
statement(s)
else: statement(s)
NESTED IF STATEMENT
nestinput = int(input("Enter the Number"))
if nestinput < 1000:
print ("Expression value is less than 1000")
if nestinput == 500:
print ("Expected divided by 2")
elif nestinput == 100:
print ("The value is 1/10 of expected value")
elif nestinput == 50:
print ("The value is 1/20 of expected value")
elif nestinput < 50:
print ("Very Low value")
else:
print ("It more than the expected value")
print ("Nested statements are working")
LOOPING STATEMENTS

Loop Type Description

Repeats a statement or group of statements while a given condition is TRUE. It tests


while loop
the condition before executing the loop body.

Executes a sequence of statements multiple times and abbreviates the code that
for loop
manages the loop variable.

nested loops You can use one or more loop inside any another while, for or do..while loop.
LOOP CONTROL STATEMENTS

Control
Description
Statement
Terminates the loop statement and transfers execution to the
break statement
statement immediately following the loop.
Causes the loop to skip the remainder of its body and immediately
continue statement
retest its condition prior to reiterating.
The pass statement in Python is used when a statement is required
pass statement syntactically but you do not want any command or code to
execute.
WHILE LOOP

while expression:
statement(s)
Here, statement(s) may be a single statement or a block of statements.
The condition may be any expression, and true is any non-zero value.
The loop iterates while the condition is true.
WHILE LOOP

val=int(input("Enter the Number which is less than 15 and greated than 5:"))
while(val > 2):
print('value is=', val)
val=val-1
print('while loop is working')
USING ELSE STATEMENT WITH LOOPS

 Python supports to have an else statement associated with a loop


statement.
 If the else statement is used with a for loop, the else statement is executed when
the loop has exhausted iterating the list.
 If the else statement is used with a while loop, the else statement is executed
when the condition becomes false.
WHILE LOOP WITH ELSE

myvalue=int(input("Enter the value:"))


while (myvalue <= 5): Enter the value:-1
The value is lessthan 5 which is : -1
print('The value is lessthan 5 which is :', myvalue) The value is lessthan 5 which is : 0
The value is lessthan 5 which is : 1
myvalue=myvalue+1 The value is lessthan 5 which is : 2
else: The value is lessthan 5 which is : 3
The value is lessthan 5 which is : 4
print("The value is greater than five") The value is lessthan 5 which is : 5
The value is greater than five
FOR LOOP

for iterating_var in sequence:


statements(s)
FOR LOOP

mylistvalues = ['chennai','bangalore','hyderabad','patna','trichy','madurai']
for i in mylistvalues:
print ("The city name :", i) The city name : chennai
The city name : bangalore
The city name : hyderabad
The city name : patna
print('Thank you') The city name : trichy
The city name : madurai
Thank you
FOR LOOP

value=int(input("Enter the number"))


for i in range(value):
print("the number:",i)
Enter the number5
the number: 0
print("working") the number: 1
the number: 2
the number: 3
the number: 4
working
FOR LOOP

value1=int(input("Enter the lower range")) Enter the lower range10


Enter the higher range20
value2=int(input("Enter the higher range")) the number: 10
the number: 11
for i in range(value1, value2): the number: 12
the number: 13
print("the number:",i) the number: 14
the number: 15
the number: 16
print("working") the number: 17
the number: 18
the number: 19
working
FOR LOOP

for index in range(limit1, limit2, [optional increment / decrement)


for i in range(10,20)
for i in range(10,20,2)
for I in range(20,10,-1)
NESTED LOOPS

while expression:
while expression:
statement(s)
statement(s)

for iterating_var in sequence:


for iterating_var in sequence:
statements(s)
statements(s)
NESTED LOOPS

i=2
while(i < 100):
j=2
while(j <= ( I / j) ):
if not( I %j ):
break
j=j+1
if (j > i/j) :
print (i, " is prime“)
i=i+1
BREAK AND CONTINUE

 The most common use for break is when some external condition
is triggered requiring a hasty exit from a loop. The break statement
can be used in both while and for loops.

 It returns the control to the beginning of the while loop..


The continue statement rejects all the remaining statements in the
current iteration of the loop and moves the control back to the top
of the loop.
BREAK AND CONTINUE
1
2
3
for i in range(1,10): for i in range(1,10): 4
if(i==5): if(i==5): Bye break
1
break continue 2
else: 3
else: 4
print(i) print(i) 6
7
print("Bye break") print("Bye continue") 8
9
Bye continue
PASS

 The pass statement is for letter in 'Python':


if letter == 'h':
a null operation; nothing pass
print ('This is pass block')
happens when it executes. print ('Current Letter :', letter)
The pass is also useful in print ("Good bye!")
Current Letter : P
places where your code will Current Letter : y
eventually go, but has not Current Letter : t
This is pass block
been written yet Current Letter : h
Current Letter : o
Current Letter : n
Good bye!
STRINGS

 Strings are amongst the most popular types in Python. Strings can be
created simply by enclosing characters in quotes. Python treats single
quotes the same as double quotes. Creating strings is as simple as
assigning a value to a variable.
 Python does not support a character type; these are treated as strings of
length one, thus also considered a substring.
STRING UPDATE

 "update" an existing string by (re)assigning a variable to another string. The new value
can be related to its previous value or to a completely different string altogether.

var1 = 'Hello Shanmuganeethi.v!'


print ("Updated String :- ", var1[:6] + 'Python‘)

Updated String :- Hello Python


ESCAPE SEQUENCE
Backslash notation Hexadecimal character Description
\a 0x07 Bell or alert
\b 0x08 Backspace
\cx Control-x
\C-x Control-x
\e 0x1b Escape
\f 0x0c Formfeed
\M-\C-x Meta-Control-x
\n 0x0a Newline
\nnn Octal notation, where n is in the range 0.7
\r 0x0d Carriage return
\s 0x20 Space
\t 0x09 Tab
\v 0x0b Vertical tab
\x Character x
\xnn Hexadecimal notation, where n is in the range 0.9, a.f, or A.F
STRING SPECIAL OPERATORS
Operator Description Example
+ Concatenation - Adds values on either side of the operator a + b will give HelloPython

* Repetition - Creates new strings, concatenating multiple copies of the same a*2 will give -HelloHello
string
[] Slice - Gives the character from the given index a[1] will give e

[ :] Range Slice - Gives the characters from the given range a[1:4] will give ell

in Membership - Returns true if a character exists in the given string H in a will give 1

not in Membership - Returns true if a character does not exist in the given string M not in a will give 1

r/R Raw String - Suppresses actual meaning of Escape characters. The syntax for raw print r'\n' prints \n and print
strings is exactly the same as for normal strings with the exception of the raw R'\n'prints \n
string operator, the letter "r," which precedes the quotation marks. The "r" can
be lowercase (r) or uppercase (R) and must be placed immediately preceding the
first quote mark.

% Format - Performs String formatting


FORMAT STRING
Format Symbol Conversion
%c character
%s string conversion via str() prior to formatting
%i signed decimal integer
%d signed decimal integer
%u unsigned decimal integer
%o octal integer
%x hexadecimal integer (lowercase letters)
%X hexadecimal integer (UPPERcase letters)
%e exponential notation (with lowercase 'e')
%E exponential notation (with UPPERcase 'E')
%f floating point real number
%g the shorter of %f and %e
%G the shorter of %f and %E
STRING METHODS
capitalize()
Capitalizes first letter of string
center(width, fillchar)
Returns a space-padded string with the original string centered to a total of width columns.
count(str, beg= 0,end=len(string))
Counts how many times str occurs in string or in a substring of string if starting index beg and ending index end are given.

endswith(suffix, beg=0, end=len(string))


Determines if string or a substring of string (if starting index beg and ending index end are given) ends with suffix; returns
true if so and false otherwise.
expandtabs(tabsize=8)
Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided.
find(str, beg=0 end=len(string))
Determine if str occurs in string or in a substring of string if starting index beg and ending index end are given returns
index if found and -1 otherwise.
STRING METHODS
index(str, beg=0, end=len(string))
Same as find(), but raises an exception if str not found.
isalnum()
Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.
isalpha()
Returns true if string has at least 1 character and all characters are alphabetic and false otherwise.
isdigit()
Returns true if string contains only digits and false otherwise.
islower()
Returns true if string has at least 1 cased character and all cased characters are in lowercase and false
otherwise.
isspace()
Returns true if string contains only whitespace characters and false otherwise.
istitle()
Returns true if string is properly "titlecased" and false otherwise.
STRING METHODS
isupper()
Returns true if string has at least one cased character and all cased characters are in uppercase and false
otherwise.
join(seq)
Merges (concatenates) the string representations of elements in sequence seq into a string, with separator
string.
len(string)
Returns the length of the string
ljust(width[, fillchar])
Returns a space-padded string with the original string left-justified to a total of width columns.
lower()
Converts all uppercase letters in string to lowercase.
lstrip()
Removes all leading whitespace in string.
STRING METHODS
maketrans()
Returns a translation table to be used in translate function.
max(str)
Returns the max alphabetical character from the string str.
min(str)
Returns the min alphabetical character from the string str.
replace(old, new [, max])
Replaces all occurrences of old in string with new or at most max occurrences if max given.
rfind(str, beg=0,end=len(string))
Same as find(), but search backwards in string.
rindex( str, beg=0, end=len(string))
Same as index(), but search backwards in string.
rjust(width,[, fillchar])
Returns a space-padded string with the original string right-justified to a total of width columns.
rstrip()
Removes all trailing whitespace of string.
STRING METHODS
split(str="", num=string.count(str))
Splits string according to delimiter str (space if not provided) and returns list of substrings; split into at most
num substrings if given.
splitlines( num=string.count('\n'))
Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed.
startswith(str, beg=0,end=len(string))
Determines if string or a substring of string (if starting index beg and ending index end are given) starts with
substring str; returns true if so and false otherwise.
strip([chars]) Performs both lstrip() and rstrip() on string
swapcase() Inverts case for all letters in string.
title() Returns "titlecased" version of string, that is, all words begin with uppercase and the rest are lowercase.
translate(table, deletechars="")
Translates string according to translation table str(256 chars), removing those in the del string.
STRING METHODS

upper()
Converts lowercase letters in string to uppercase.
zfill (width)
Returs original string leftpadded with zeros to a total of width characters;
intended for numbers, zfill() retains any sign given (less one zero).
isdecimal()
Returns true if a unicode string contains only decimal characters and false
otherwise.
THANK YOU

You might also like