Fatskills
Practice. Master. Repeat.
Study Guide: Python Programming: Strings and Functions in Python
Source: https://www.fatskills.com/python/chapter/python-programming-strings-and-functions-in-python

Python Programming: Strings and Functions in Python

By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.

⏱️ ~9 min read

In the previous chapters, we have already discussed about how to declare string and numbers in Python. In this chapter, we are going to discuss about various Python in-built mathematical, random number, trigonometric functions and their use on numbers and in-built string methods.

Mathematical functions

Function

Returns ( description )

abs(x)

This function determines the absolute value of x, which is the (positive) distance between x and zero.

ceil(x)

This function determines the ceiling of x, which is the smallest integer not less than x.

cmp(x, y)

This function returns values as -1, 0 and 1. It returns-1 if x < y, 0 if x == y, or 1 if x > y.

exp(x)

This function determines the exponential of x: ex.

fabs(x)

This function determines the absolute value of x.

floor(x)

This function determines the floor of x, which is the largest integer not greater than x.

log(x)

This function determines the natural logarithm of x, for x> 0.

log10(x)

This function determines the base-10 logarithm of x for x> 0.

max (x1, x2,..)

This function determines the largest of its arguments, which is the value closest to positive infinity.

min (x1, x2,..)

This function determines the smallest of its arguments, which is the value closest to negative infinity

modf(x)

This function determines 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 by the function.

pow(x, y)

This function determines the value of xy.

round(x [,n])

In this function, 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)

This function determines the square root of x for x > 0.

 

Random Number functions

 

 

Function

Description

choice(seq)

This function returns a random item from a list, tuple, or string.

randrange ([start,] stop [,step])

This function returns a randomly selected element from range (start, stop, step).

random()

This function returns a random float r, such that 0 is less than or equal to r and r is less than 1.

seed([x])

This function sets the integer starting value used in generating random numbers. Call this function before calling any other random module function. Returns None.

shuffle(lst)

This function is used to randomize the items of a list in place. It returns Nothing.

uniform(x, y)

This function returns a random float r, such that x is less than or equal to r and r is less than y.

 


Trigonometric functions

 

 

Function

Description

acos(x)

This Python in-built trigonometric function returns the arc cosine of x, in radians.

asin(x)

This Python in-built trigonometric function returns the arc sine of x, in radians.

atan(x)

This Python in-built trigonometric function returns the arc tangent of x, in radians.

atan2(y, x)

This Python in-built trigonometric function returns atan(y / x), in radians.

cos(x)

This Python in-built trigonometric function returns the cosine of x radians.

hypot(x, y)

This Python in-built trigonometric function returns the Euclidean norm, sqrt(x*x + y*y).

sin(x)

This Python in-built trigonometric function returns the sine of x radians.

tan(x)

This Python in-built trigonometric function returns the tangent of x radians.

degrees(x)

This Python in-built trigonometric function converts angle x from radians to degrees.

radians(x)

This Python in-built trigonometric function converts angle x from degrees to radians.

 


Mathematical Constants

 

 

Constants

Description

Pi

The mathematical constant pi.

E

The mathematical constant e.

 


Python in-built String Methods

 

 

Methods

Description

capitalize()

This Python in-built function is for String which makes first letter of the string in uppercase

center(width, fillchar)

This Python in-built function for String returns a space-padded string with the original string centered to a total of width columns.

count(str, beg= 0,end=len(string))

This Python in-built function for 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.

decode(encoding='UTF-8',errors='strict')

This Python in-built function for String decodes the string using the codec registered for encoding. Encoding defaults to the default string encoding.

encode(encoding='UTF-8',errors='strict')

This Python in-built function for String returns encoded string version of string; on error, default is to raise a ValueError unless errors is given with 'ignore' or 'replace'.

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

This Python in-built function for 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)

This Python in-built function for String expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided.

find(str, beg=0 end=len(string))

This Python in-built function for 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.

index(str, beg=0, end=len(string))

This Python in-built function for String is same as find(), but raises an exception if str not found.

isalnum()

This Python in-built function for String returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.

isalpha()

This Python in-built function for String returns true if string has at least 1 character and all characters are alphabetic and false otherwise.

isdigit()

This Python in-built function for String returns true if string contains only digits and false otherwise.

islower()

This Python in-built function for String returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.

isnumeric()

This Python in-built function for String returns true if a Unicode string contains only numeric characters and false otherwise.

isspace()

This Python in-built function for String returns true if string contains only whitespace characters and false otherwise.

istitle()

This Python in-built function for String returns true if string is properly "titlecased" and false otherwise.

isupper()

This Python in-built function for String returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.

join(seq)

This Python in-built function for String merges (concatenates) the string representations of elements in sequence seq into a string, with separator string.

len(string)

This Python in-built function for String returns the length of the string

ljust(width[, fillchar])

This Python in-built function for String returns a space-padded string with the original string left-justified to a total of width columns.

lower()

This Python in-built function for String converts all uppercase letters in string to lowercase.

lstrip()

This Python in-built function for String removes all leading whitespace in string.

maketrans()

This Python in-built function for String returns a translation table to be used in translate function.

max(str)

This Python in-built function for String returns the max alphabetical character from the string str.

min(str)

This Python in-built function for String returns the min alphabetical character from the string str.

replace(old, new [, max])

This Python in-built function for String replaces all occurrences of old in string with new or at most max occurrences if max given.

rfind(str, beg=0,end=len(string))

This Python in-built function for String is same as find (), but search backwards in string.

rindex( str, beg=0, end=len(string))

This Python in-built function for String is same as index (), but search backwards in string.

rjust(width,[, fillchar])

This Python in-built function for String returns a space-padded string with the original string right-justified to a total of width columns.

rstrip()

This Python in-built function for String removes all trailing whitespace of string.

split(str="", num=string.count(str))

This Python in-built function for String 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'))

This Python in-built function for String splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed.

startswith(str, beg=0,end=len(string))

This Python in-built function for 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])

This Python in-built function for String performs both lstrip() and rstrip() on string

swapcase()

This Python in-built function for String inverts case for all letters in string.

title()

This Python in-built function for String returns "titlecased" version of string, that is, all words begin with uppercase and the rest are lowercase.

translate(table, deletechars="")

This Python in-built function for String translates string according to translation table str(256 chars), removing those in the del string.

upper()

This Python in-built function for String converts lowercase letters in string to uppercase.

zfill (width)

This Python in-built function for String returns original string leftpadded with zeros to a total of width characters; intended for numbers, zfill () retains any sign given (less one zero).

isdecimal()

This Python in-built function for String returns true if a Unicode string contains only decimal characters and false otherwise.



String Formatting Operator
Python language has the string format operator % which is unique to strings and makes up for the functions present for C language printf ().

Following is the list of such operators in Python.

 

 

Format Symbol

Conversion

%c

It converts to character

%s

string conversion via str() prior to formatting

%i

It converts to signed decimal integer

%d

It converts to signed decimal integer

%u

It converts to unsigned decimal integer

%o

It converts to octal integer

%x

It converts to hexadecimal integer (lowercase letters)

%X

It converts to hexadecimal integer (upper case letters)

%e

It converts to exponential notation (with lowercase 'e')

%E

It converts to exponential notation (with upper case 'E')

%f

It converts to floating point real number

%g

It converts to the shorter of %f and %e

%G

It converts to the shorter of %f and %E



Python code example for String Formatter


In the above example %s string formatter is used to format a string and %d is used to format an integer into a string.

Escape Characters
Python language has the following list of escape or non-printable characters that are represented with backslash notation.
An escape character gets interpreted by Python in a single quoted as well as double quoted strings.

 

 

Backslash Notation

Hexadecimal Character

Description

\a

0x07

It is used for Bell or alert.

\b

0x08

It is used for Backspace.

\cx

 

It is used for Control-x.

\C-x

 

It is used for Control-x.

\e

0x1b

It is used for Escape.

\f

0x0c

It is used for Formfeed.

\M-\C-x

 

It is used for Meta-Control-x.

\n

0x0a

It is used for Newline.

\nnn

 

It is used for Octal notation, where n is in the range 0.7.

\r

0x0d

It is used for carriage return.

\s

0x20

It is used for space.

\t

0x09

It is used for tab.

\v

0x0b

It is used for vertical tab.

\x

 

It is used for character x.

\xnn

 

It is used for hexadecimal notation, where n is in the range 0.9, a.f, or A.F