0% found this document useful (0 votes)
1 views

Built-in functions

Uploaded by

then mozhi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Built-in functions

Uploaded by

then mozhi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

BUILD – IN FUNCTION

Built-in Functions on Strings


 Function count
 Functions find and rfind
 Functions capitalize, title, lower, upper, and swapcase
 Functions islower, isupper, and istitle
 Function replace
 Functions strip, lstrip, and rstrip
 Functions split and partition
 Function join
 Functions isspace, isalpha, isdigit, and isalnum
 Function startswith and endswith
 Functions encode and decode
 List of Functions
Built-in functions that can be applied on strings.
1. function count
Suppose, we wish to find the number of occurrences of Character ‘c’ in the string
‘Encyclopedia’. To achieve this, we apply the function count with argument ‘c’ to
the string ‘Encyclopedia’:
count(): to count occurrences of a string in another string
>>> ‘Encyclopedia’.count(‘c’)
2
As an application of the function count, examine the following code intended to
find the count of all the vowels in the string ‘Encyclopedia:’:
>>> vowels = ‘aeiou’
>>> vowelCount = 0
>>> for ch in vowels:
vowelCount += ‘Encyclopedia’.count(ch)
BUILD – IN FUNCTION

>>> vowelCount
4
The system responds with 4 as the value of the vowelCount, even though the
number of vowels in the search string ‘Encyclopedia’ is 5. As the character ‘E’ was
not included in the string vowels, it was not included in counting too. To include
the count of uppercase vowels also, we just need to include vowels in uppercase
also in the string vowels:
vowels = ‘AEIOUaeiou’
rest of the code remains the same.
2. functions find and rfind
Examine the string colors. Suppose we wish to find out whether 'red' is present as a
substring in the string colors. We can do so by using the function find that returns
the index of the first occurrence of string argument 'red' in colors:
finding index of first occurrence of a string in another string
>>> colors = 'green, red, blue, red, red,
green'
>>> colors.find('red')
7
To find the last occurrence of a string, we use the function rfind that scans the
string in reversed order from the right end of the string to the beginning:
finding index of the last occurrence of a string in another string
>>> colors.rfind('red')
23
If the function find fails to find the desired substring, it
returns -1:
>>> colors.find('orange')
-1
BUILD – IN FUNCTION

3. functions capitalize, title, lower, upper, and swapcase


Python provides several functions that enable us to manipulate the case of strings.
For example, the function capitalize can be used for converting the first letter of a
string to uppercase character and converting the remaining letters in the string to
lowercase (if not already so).
transforming a str ing to sentence case
>>> 'python IS a Language'.capitalize()
'Python is a language'
Python function title can be used to capitalize the first letter of each word in a
string and change the remaining letters to lowercase (if not already so):
>>> 'python IS a PROGRAMMING Language'.title()
'Python Is A Programming Language'
Python functions lower and upper are used to convert all letters in a string to
lowercase and uppercase, respectively. Suppose we want to check for the
equivalence of a pair of email ids. Since email ids are not case sensitive, we
convert both email ids to either uppercase or lowercase before testing for equality:
>>> emailId1 = ‘[email protected]
>>> emailId2 = ‘[email protected]
>>> emailId1 == emailId2
False
>>> emailId1.lower() == emailId2.lower()
True
>>> emailId1.upper() == emailId2.upper()
True
Python function swapcase may be used to convert Lowercase letters in a string to
uppercase letters and vice Versa, for example:
>>> ‘pYTHON IS PROGRAMMING
BUILD – IN FUNCTION

LANGUAGE’.swapcase()
‘Python is programming language’
4. functions islower, isupper, and istitle
The functions islower and isupper can be used to check if all letters in a string are
in lowercase or uppercase, respectively, for example:
checking case (lower / upper ) of a string
>>> ‘python’.islower()
True
>>> ‘Python’.isupper()
False
The function istitle returns True if a string S (comprising atleast one alphabet) is in
title case, for example:
checking whether the string is in title case
>>> ‘Basic Python Programming’.istitle()
True
>>> ‘Basic PYTHON Programming’.istitle()
False
>>> ‘123’.istitle()
False
>>> ‘Book 123’.istitle()
True
5. Function replace
The function replace allows to replace part of a string by another string. It takes
two arguments as inputs. The first argument is used to specify the substring that is
to be replaced. The second argument is used to specify the string that replaces the
first string. For example:
replacing a substring with another string
BUILD – IN FUNCTION

>>> message = ‘Amey my friend, Amey my


Guide’
>>> message.replace(‘Amey’, ‘Vihan’)‘Vihan my friend, Vihan my guide’
6. Functions strip, lstrip, and rstrip
The functions lstrip and rstrip remove whitespaces from the beginning and end,
respectively. The function strip removes whitespaces from the beginning as well
As the end of a string. We may choose to remove any Other character(s) from the
beginning or end by explicitly Passing the character(s) as an argument to the
function.The following examples illustrate the use of the functions lstrip, rstrip,
and strip:
removing whitespace from the beginning/ end of a string
>>> ‘ Hello How are you! ‘.lstrip()
‘Hello How are you! ‘
>>> ‘ Hello How are you! ‘.rstrip()
‘ Hello How are you!’
>>> ‘ Hello How are you! ‘.strip()
‘Hello How are you!’
7. Functions split and partition
The function split enables us to split a string into a list of strings based on a
delimiter. For example:
splitting a string into substrings
>>> colors = ‘Red, Green, Blue, Orange,
Yellow, Cyan’
>>> colors.split(‘,’)
[‘Red’, ‘ Green’, ‘ Blue’, ‘ Orange’, ‘Yellow’, ‘ Cyan’]
Note that the function split outputs a sequence of strings enclosed in square
brackets. A sequence of objects enclosed in square brackets defines a list.
BUILD – IN FUNCTION

8. Function join
Python function join returns a string comprising elements of a sequence separated
by the specified Delimiter. For example,
joining a sequence of strings
>>> ‘ > ‘.join([‘I’, ‘am’, ‘ok’])
‘I > am > ok’
>>> ‘ ‘.join((‘I’, ‘am’, ‘ok’))
‘I am ok’
>>> ‘ > ‘.join(“’I’, ‘am’, ‘ok’”)
“’ > I > ‘ > , > > ‘ > a > m > ‘ > , > > ‘ >O > k > ‘”
In the first example, the sequence comprises three elements, namely, ‘I’, ‘am’, and
‘ok’, which are combined to form the string ‘I > am > ok’. In the Second example,
we use space as a delimiter instead of >. In the third example, each character in the
string “’I > am > ok’” is an element of the sequence of Characters in “’I > am >
ok’”.
9. Functions isspace, isalpha, isdigit, and Isalnum
The functions isspace, isalpha, isdigit, and isalnum enable us to check whether a
value is of the desire type. For example, we can check whether the name entered
by a user contains only alphabets as follows:
does a string comprises alphabets, digits, or whitespaces Only ?
>>> name = input(‘Enter your name : ‘)
Enter your name : Nikhil
>>> name.isalpha()
True
>>> name = input(‘Enter your name : ‘)
Enter your name : Nikhil Kumar
>>> name.isalpha()
BUILD – IN FUNCTION

False
Note that the blank character is not an alphabet. Similarly, to check the validity of
a mobile number, we may want it to be a string of length 10 comprising of digits
only. This can be achieved using functions
isdigit and len:
>>> mobileN = input(‘Enter mobile no : ‘)
Enter mobile no : 1234567890
>>> mobileN.isdigit() and len(mobileN)
== 10
True
Python function isspace is used to check if the string Comprises of all whitespaces:
check for a whitespace only string
>>> ‘ \n\t ‘.isspace()
True
The function isalnum checks whether a string comprises of alphabets and digits
only. For example, if the password is allowed to comprise of only alphabets and
digits, we may use the function isalnum to ensure this constraint for a user
specified password:
check for an alphanumeric string
>>> password = input(‘Enter password : ‘)
Enter password : Kailash107Ganga
>>> password.isalnum()
True
>>> password = input(‘Enter password : ‘)
Enter password : Kailash 107 Ganga
>>> password.isalnum()
False
BUILD – IN FUNCTION

10.Function startswith and endswith


Suppose we want to check if the last name of a person is Talwar. We can do this
using Python function Endswith as follows:
checking whether a string starts or ends with a particular strings
>>> name = ‘Ankita Narain Talwar’
>>> name.endswith(‘Talwar’)
True
Similarly, to find whether a person’s name begins with Dr. we can use the function
startswith as follows:
>>> name = ‘Dr. Vihan Garg’
>>> name.startswith(‘Dr. ‘)
True
>>> name = ‘ Dr. Amey Gupta’
>>> name.startswith(‘Dr. ‘)
False
11.Functions encode and decode
Sometimes, we need to transform data from one format to another for the sake of
compatibility. Thus, we use, Python function encode that returns the encoded
version of a string, based on the given encoding scheme. another function decode
(reverse of function encode) returns the decoded string, for example:
encoding and decoding a string
>>> str1 = ‘message’.encode(‘utf32’)
>>> str1
b'\xff\xfe\x00\x00m\x00\x00\x00e\x00\x00\x
00s\x00\x00\x00s\x00\x00\x00a\x00\x00\x00g
\x00\x00\x00e\x00\x00\x00'
>>> str1.decode('utf32')
BUILD – IN FUNCTION

'message'
One may also use alternative coding schemes such as utf8 and utf16.

You might also like