You are on page 1of 46

3.

String and Boolean


Manipulations
1. Python Strings and Inbuilt functions
2. Boolean Variables

Strings
Strings in python are surrounded by either single quotation marks, or double quotation marks.
'python' is the same as "python".
You can display a string literal with the print() function:

In [13]: 1 print("python")
2 print('python')

python
python

Some basic operations using python strings:

Concatenation:
when we use + operated between a strings then it act as concatenation and add both string.

In [1]: 1 var1 = "Python1"


2 var2 = "Python2"
3 print(var1+var2)
4 print(var1+" "+var2)

Python1Python2
Python1 Python2

String Repetition

In [2]: 1 print("Python "*5)

Python Python Python Python Python


Different Quotes in PYTHON:

In [3]: 1 PyStr="PYTHON"
2 print(PyStr,type(PyStr))
3 PyStr='PYTHON'
4 print(PyStr,type(PyStr))
5 PyStr="""PYTHON"""
6 print(PyStr,type(PyStr))
7 PyStr='''PYTHON'''
8 print(PyStr,type(PyStr))

PYTHON <class 'str'>


PYTHON <class 'str'>
PYTHON <class 'str'>
PYTHON <class 'str'>

Assign a string to a variable and Re-Assigning


To assign a value to Python variables, type the value after the equal sign(=).

In [6]: 1 #Example-1 (We can do reasing for total string)


2 MyStr="PYTHON"
3 print(MyStr)
4 MyStr="Machine Leaning"
5 print(MyStr)

PYTHON
Machine Leaning

In [4]: 1 #Example-2
2 MyStr="PYTHON"
3 print(MyStr)
4 print(MyStr[-1])
5 MyStr[-1]="R"
6 print(MyStr)

PYTHON
N

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [4], in <cell line: 5>()
3 print(MyStr)
4 print(MyStr[-1])
----> 5 MyStr[-1]="R"
6 print(MyStr)

TypeError: 'str' object does not support item assignment


Multiline Strings
You can assign a multiline string to a variable by using three quotes:

Example
You can use three double quotes:

In [4]: 1 a = """Lorem ipsum dolor sit amet,


2 consectetur adipiscing elit,
3 sed do eiusmod tempor incididunt
4 ut labore et dolore magna aliqua."""
5 print(a)

Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.

Example
Or three single quotes:

In [7]: 1 a = '''Lorem ipsum dolor sit amet,


2 consectetur adipiscing elit,
3 sed do eiusmod tempor incididunt
4 ​
5 ut labore et dolore magna aliqua.'''
6 print(a)

Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt

ut labore et dolore magna aliqua.

Note: in the result, the line breaks are inserted at the same position as in the code.

Looping Through a String


Since strings are arrays, we can loop through the characters in a string, with a for loop.
In [17]: 1 MyStr = "PYTHON"
2 for i in MyStr:
3 print(i)

P
Y
T
H
O
N

String Length
To get the length of a string, use the len() function.

In [19]: 1 MyStr = "PYTHON"


2 print(len(MyStr))

Check String
To check if a certain phrase or character is present in a string, we can use the in keyword.

In [21]: 1 txt ="Good morning master"


2 print("Good" in txt)
3 print("good" in txt)

True
False

Using in an if statement:

In [30]: 1 txt ="Good morning master"


2 if "Good" in txt:
3 print("\"Good\" is there")
4 else:
5 print("\"good\" is not there")

"Good" is there

Check if NOT
To check if a certain phrase or character is NOT present in a string, we can use the keyword
not in.
In [33]: 1 txt ="Good morning master"
2 if "good" not in txt:
3 print("good is not there ")
4 else:
5 print("\"good\" is there")

good is not there

Slicing:

What is String Slicing?


To cut a substring from a string is called string slicing. OR
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part of the
string.
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.

String Indices or Indexing


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

If our string in "PYTHON" then +ve and -ve indexes will assign like below:

P Y T H O N

0 1 2 3 4 5

-6 -5 -4 -3 -2 -1
In [14]: 1 #+ve slicing
2 a = "PYTHON"
3 print(a[0])
4 print(a[1])
5 print(a[2])
6 print(a[3])
7 print(a[4])
8 print(a[5])
9 print(a[6])

P
Y
T
H
O
N

---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
Input In [14], in <cell line: 9>()
7 print(a[4])
8 print(a[5])
----> 9 print(a[6])

IndexError: string index out of range

In [15]: 1 #-ve slicing


2 print(a[-1])
3 print(a[-2])
4 print(a[-3])
5 print(a[-4])
6 print(a[-5])
7 print(a[-6])
8 print(a[-7])

N
O
H
T
Y
P

---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
Input In [15], in <cell line: 8>()
6 print(a[-5])
7 print(a[-6])
----> 8 print(a[-7])

IndexError: string index out of range


Note : When we give index more then index of string then it will give IndexError: string index
out of range.

Slice From the Start


By leaving out the start index, the range will start at the first character:

In [16]: 1 print(a[:4])

PYTH

Slice To the End


By leaving out the end index, the range will go to the end:

In [17]: 1 print(a[2:])

THON

Negative Indexing
Use negative indexes to start the slice from the end of the string:

In [19]: 1 print(a[-6:-2])

PYTH

Wrt a program to check either given string is a" Palindrome or not..?

In [215]: 1 s = "level"
2 if s == s[::-1]:
3 print("Yess ....")
4 else:
5 print("Noooooo...")

Yess ....

In [216]: 1 s = "Rakesh"
2 if s == s[::-1]:
3 print("Yess ....")
4 else:
5 print("Noooooo...")

Noooooo...
What is difference between ASCII and UNICODE string.?

ASCII (American Standard Code for Information Interchange) :

It is a character encoding standard or format that uses numbers from 0 to 127 to represent
English characters.
ASCII value of "A" is 65
ASCII value of "a"is 97

UNICODE:

This UNICODE is superset of ASCII...


which are numbers from 0 through 0x10FFFF (1,114,111 decimal).

chr() and ord() two methods which will provide Charcter based on ASCII value and ASCII value
based on character represntly.

In [22]: 1 print(ord("A"))
2 print(chr(65))

65
A

In [30]: 1 print(ord("అ"))

3077

In [35]: 1 amma = "అమ్మ "


In [45]: 1 print(amma[0])
2 print(amma[1])
3 print(amma[2])
4 print(amma[3])
5 print(amma[4])




---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
Input In [45], in <cell line: 5>()
3 print(amma[2])
4 print(amma[3])
----> 5 print(amma[4])

IndexError: string index out of range

String Format
As we learned in the Python Variables chapter, we cannot combine strings and numbers like
this:

In [47]: 1 age = 25
2 print(" My age is "+age)

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [47], in <cell line: 2>()
1 age = 25
----> 2 print(" My age is "+age)

TypeError: can only concatenate str (not "int") to str

But we can combine strings and numbers by using the format() method!

The format() method takes the passed arguments, formats them, and places them in the string
where the placeholders {} are:

In [52]: 1 name = "Rakesh"


2 age = 25
3 place = "Hyderbad"
4 print("Hello, My name is {} and my age is {} and i live in {}...!".format

Hello, My name is Rakesh and my age is 25 and i live in Hyderbad...!


You can use index numbers {0} to be sure the arguments are placed in the correct
placeholders:

In [54]: 1 name = "Rakesh"


2 age = 25
3 place = "Hyderbad"
4 print("Hello, My name is {2} and my age is {0} and i live in {1}...!".for

Hello, My name is Rakesh and my age is 25 and i live in Hyderbad...!

String Methods
Python has a set of built-in methods that you can use on strings.

Note : All string methods return new values. They do not change the original string until we
asign it to original variable.

All Methods:
S.NO Method Description

01 capitalize() Converts the first character to upper case

02 casefold() Converts string into lower case.

03 count() Returns the number of times a specified value occurs in a string.

04 startswith() Returns true if the string starts with the specified value

05 endswith() Returns true if the string ends with the specified value.

06 expandtabs() Sets the tab size of the string

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

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

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

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

11 join() This method takes all items in an iterable and joins them into one string.

12 format() Formats specified values in a string.

13 lower() Converts a string into lower case

14 upper() Converts a string into upper case

15 rjust() Returns a right justified version of the string.

16 ljust() Returns a left justified version of the string.

17 center() Returns a centered string.

18 lstrip() Returns a left trim version of the string.


S.NO Method Description

19 rstrip() Returns a right trim version of the string.

20 strip() Returns a trimmed version of the string.

21 replace() This method replaces a specified phrase with another specified phrase.

22 split() Splits the string at the specified separator, and returns a list

23 rsplit() Splits the string at the specified separator, and returns a list

24 splitlines() Splits the string at line breaks and returns a list

25 title() This method make upper case of starting letter of each word in sentance.

26 zfill() This method adds zeros (0) at the beginning of the string.

27 swapcase() Swaps cases, lower case becomes upper case and vice versa.

28 isalnum() It checks whether the string consists of alphanumeric characters.

29 isalpha() Returns True if all characters in the string are in the alphabet.

30 isascii() Returns True if all characters in the string are ascii characters.

31 isdecimal() Returns True if all characters in the string are decimals.

32 isdigit() Checks whether the string consists of digits only.

33 isidentifier() Returns True if the string is an identifier.

34 islower() Checks whether the string consists of lower case only.

35 isupper() Checks whether the string consists of upper case only.

36 isspace() Returns True if all characters in the string are whitespaces.

37 isprintable() Returns True if all characters in the string are printable

38 isnumeric() Returns True if all characters in the string are numeric

39 istitle() Returns True if the string follows the rules of a title

40 maketrans() Returns a translation table to be used in translations

41 translate() Returns a translated string

01. capitalize() :
Converts the first character to upper case and rest to lower..!

In [6]: 1 #Example -1 : General example


2 s = "python is a programming language"
3 print(s.capitalize())

Python is a programming language


In [3]: 1 #Example -2 :The first character is converted to upper case, and the rest
2 s = "python is a Programming Language"
3 print(s.capitalize())

Python is a programming language

In [5]: 1 #example -3: See what happens if the first character is a number:
2 s = "25 Is my Age"
3 print(s.capitalize())

25 is my age

02. casefold():
The casefold() method returns a string where all the characters are lower case.
This method is similar to the lower() method, but the casefold() method is stronger, more
aggressive, meaning that it will convert more characters into lower case, and will find more
matches when comparing two strings and both are converted using the casefold() method.

In [1]: 1 txt = "Hello, And Welcome To My World!"


2 print(txt.casefold())

hello, and welcome to my world!

03. count():
string.count(value, start, end)

value : Required. A String. The string to value to search for


start : Optional. An Integer. The position to start the search. Default is 0
end : Optional. An Integer. The position to end the search. Default is the end of the string

The count() method returns the number of times a specified value appears in the string.

In [2]: 1 txt = "I love apples, apple are my favorite fruit"


2 x = txt.count("apple")
3 print(x)

In [3]: 1 #Search from position 10 to 24:


2 txt = "I love apples, apple are my favorite fruit"
3 x = txt.count("apple", 10, 24)
4 print(x)

1
04. startswith():
string.startswith(value, start, end)

value : Required. The value to check if the string starts with


start : Optional. An Integer specifying at which position to start the search
end : Optional. An Integer specifying at which position to end the search

The startswith() method returns True if the string starts with the specified value, otherwise
False.

In [7]: 1 txt = "Hello, welcome to my world."


2 x = txt.startswith("Hello")
3 print(x)

True

In [8]: 1 #Check if position 7 to 20 starts with the characters "wel":


2 txt = "Hello, welcome to my world."
3 x = txt.startswith("wel", 7, 20)
4 print(x)

True

In [9]: 1 PyTxt="Python programming is easy."


2 print(PyTxt.startswith('programming is', 7))
3 print(PyTxt.startswith('programming is', 7, 19))
4 print(PyTxt.startswith('programming is', 7, 22))

True
False
True

05. endswith():
string.endswith(value, start, end)

value : Required. The value to check if the string starts with


start : Optional. An Integer specifying at which position to start the search
end : Optional. An Integer specifying at which position to end the search

The endswith() method returns True if the string ends with the specified value, otherwise
False.
In [11]: 1 txt = "Hello, welcome to my world."
2 x = txt.endswith(".")
3 print(x)

True

In [12]: 1 #Check if the string ends with the phrase "my world.":
2 txt = "Hello, welcome to my world."
3 x = txt.endswith("my world.")
4 print(x)

True

In [13]: 1 #Check if position 5 to 11 ends with the phrase "my world.":


2 txt = "Hello, welcome to my world."
3 x = txt.endswith("my world.", 5, 11)
4 print(x)

False

06. expandtabs():
string.expandtabs(tabsize)

The expandtabs() method sets the tab size to the specified number of whitespaces.
tabsize : A number specifying the tabsize. Default tabsize is 8

In [15]: 1 txt = "H\te\tl\tl\to"


2 x = txt.expandtabs()
3 print(x)

H e l l o

In [16]: 1 txt = "H\te\tl\tl\to"


2 x = txt.expandtabs(8)
3 print(x)

H e l l o

In [17]: 1 txt = "H\te\tl\tl\to"


2 x = txt.expandtabs(4)
3 print(x)

H e l l o
In [19]: 1 txt = "H\te\tl\tl\to"
2 print(txt)

H e l l o

In [18]: 1 txt = "H\te\tl\tl\to"


2 print(txt)
3 print(txt.expandtabs())
4 print(txt.expandtabs(2))
5 print(txt.expandtabs(4))
6 print(txt.expandtabs(10))

H e l l o
H e l l o
H e l l o
H e l l o
H e l l o

Finding Substrings:
In PYTHON programming to find sub strings we can use the following 4 methods:
Forward direction:

21.find() 22.index()

Backward direction:

23.rfind() 24.rindex()

07. find():
string.find(value, start, end)

value : Required. The value to search for


start : Optional. Where to start the search. Default is 0
end : Optional. Where to end the search. Default is to the end of the string

The find() method finds the first occurrence of the specified value.
The find() method returns -1 if the value is not found.
The find() method is almost the same as the index() method, the only difference is that the
index() method raises an exception if the value is not found. (See example below)

In [20]: 1 txt = "Hello, welcome to my world."


2 x = txt.find("welcome")
3 print(x)

7
In [21]: 1 #Where in the text is the first occurrence of the letter "e"?:
2 txt = "Hello, welcome to my world."
3 x = txt.find("e")
4 print(x)

In [22]: 1 #Where in the text is the first occurrence of the letter "e" when you onl
2 txt = "Hello, welcome to my world."
3 x = txt.find("e", 5, 10)
4 print(x)

In [4]: 1 #If the value is not found, the find() method returns -1, but the index()
2 txt = "Hello, welcome to my world."
3 print(txt.find("q"))

-1

08. index():
string.index(value, start, end)

value : Required. The value to search for


start : Optional. Where to start the search. Default is 0
end : Optional. Where to end the search. Default is to the end of the string

The index() method finds the first occurrence of the specified value.
The index() method raises an exception if the value is not found.
The index() method is almost the same as the find() method, the only difference is that the
find() method returns -1 if the value is not found. (See example below)

In [24]: 1 txt = "Hello, welcome to my world."


2 x = txt.index("welcome")
3 print(x)

In [25]: 1 #Where in the text is the first occurrence of the letter "e"?:
2 txt = "Hello, welcome to my world."
3 x = txt.index("e")
4 print(x)

1
In [26]: 1 #Where in the text is the first occurrence of the letter "e" when you onl
2 txt = "Hello, welcome to my world."
3 x = txt.index("e", 5, 10)
4 print(x)

In [5]: 1 #If the value is not found, the find() method returns -1, but the index()
2 txt = "Hello, welcome to my world."
3 print(txt.index("q"))

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [5], in <cell line: 3>()
1 #If the value is not found, the find() method returns -1, but the in
dex() method will raise an exception:
2 txt = "Hello, welcome to my world."
----> 3 print(txt.index("q"))

ValueError: substring not found

09. rfind():
string.rfind(value, start, end)

value : Required. The value to search for


start : Optional. Where to start the search. Default is 0
end : Optional. Where to end the search. Default is to the end of the string

The rfind() method finds the last occurrence of the specified value.
The rfind() method returns -1 if the value is not found.
The rfind() method is almost the same as the rindex() method. See example below.

In [29]: 1 txt = "Mi casa, su casa."


2 x = txt.rfind("casa")
3 print(x)

12

In [30]: 1 txt = "Mi casa, su casa."


2 x = txt.find("casa")
3 print(x)

3
In [31]: 1 #Where in the text is the last occurrence of the letter "e"?:
2 txt = "Hello, welcome to my world."
3 x = txt.rfind("e")
4 print(x)

13

In [32]: 1 #Where in the text is the last occurrence of the letter "e" when you only
2 txt = "Hello, welcome to my world."
3 x = txt.rfind("e", 5, 10)
4 print(x)

In [33]: 1 #If the value is not found, the rfind() method returns -1, but the rindex
2 txt = "Hello, welcome to my world."
3 print(txt.rfind("q"))
4 print(txt.rindex("q"))

-1

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [33], in <cell line: 4>()
2 txt = "Hello, welcome to my world."
3 print(txt.rfind("q"))
----> 4 print(txt.rindex("q"))

ValueError: substring not found

10. rindex():
string.rindex(value, start, end)

value : Required. The value to search for


start : Optional. Where to start the search. Default is 0
end : Optional. Where to end the search. Default is to the end of the string

The rindex() method finds the last occurrence of the specified value.
The rindex() method raises an exception if the value is not found.
The rindex() method is almost the same as the rfind() method. See example below.

In [34]: 1 txt = "Mi casa, su casa."


2 x = txt.rindex("casa")
3 print(x)

12
In [35]: 1 txt = "Mi casa, su casa."
2 x = txt.index("casa")
3 print(x)

In [36]: 1 #Where in the text is the last occurrence of the letter "e"?:
2 txt = "Hello, welcome to my world."
3 x = txt.rindex("e")
4 print(x)

13

In [37]: 1 #Where in the text is the last occurrence of the letter "e" when you only
2 txt = "Hello, welcome to my world."
3 x = txt.rindex("e", 5, 10)
4 print(x)

In [38]: 1 #If the value is not found, the rfind() method returns -1, but the rindex
2 txt = "Hello, welcome to my world."
3 print(txt.rfind("q"))
4 print(txt.rindex("q"))

-1

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [38], in <cell line: 4>()
2 txt = "Hello, welcome to my world."
3 print(txt.rfind("q"))
----> 4 print(txt.rindex("q"))

ValueError: substring not found

11. join():
The join() method takes all items in an iterable and joins them into one string.
A string must be specified as the separator.

Note : When using a dictionary as an iterable, the returned values are the keys, not the
values.

In [39]: 1 myTuple = ("John", "Peter", "Vicky")


2 x = "#".join(myTuple)
3 print(x)

John#Peter#Vicky
In [40]: 1 myDict = {"name": "rakesh", "country": "india","age":25}
2 mySeparator = " "
3 x = mySeparator.join(myDict)
4 print(x)

name country age

12. format():
string.format(value1, value2...)

value1, value2... :
Required. One or more values that should be formatted
and inserted in the string.
The values are either a list of values separated by c
ommas, a key=value list, or a combination of both.
The values can be of any data type.

The format() method formats the specified value(s) and insert them inside the string's
placeholder.
The placeholder is defined using curly brackets: {}. Read more about the placeholders in
the Placeholder section below.
The format() method returns the formatted string.

In [43]: 1 # The placeholders can be identified using named indexes {price}, numbere
2 txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age = 36)
3 txt2 = "My name is {0}, I'm {1}".format("John",36)
4 txt3 = "My name is {}, I'm {}".format("John",36)
5 ​
6 print(txt1)
7 print(txt2)
8 print(txt3)

My name is John, I'm 36


My name is John, I'm 36
My name is John, I'm 36

13. lower():
The lower() method returns a string where all characters are lower case.

In [45]: 1 txt = "Hello my FRIENDS"


2 x = txt.lower()
3 print(x)

hello my friends
14. upper():
The upper() method returns a string where all characters are in upper case.

In [46]: 1 txt = "Hello my FRIENDS"


2 x = txt.upper()
3 print(x)

HELLO MY FRIENDS

15. rjust():
string.rjust(length, character)

The rjust() method will right align the string, using a specified character (space is default)
as the fill character.

In [8]: 1 txt = "Python"


2 print(txt,len(txt))
3 txt1 = txt.rjust(20)
4 print(txt1,len(txt1))
5 print(txt.rjust(20,"%"),len(txt.rjust(20,"%")))

Python 6
Python 20
%%%%%%%%%%%%%%Python 20

16. ljust():
string.ljust(length, character)

The ljust() method will left align the string, using a specified character (space is default) as
the fill character.

In [49]: 1 txt = "Python"


2 print(txt,len(txt))
3 txt1 = txt.ljust(20)
4 print(txt1,len(txt1))
5 print(txt.ljust(20,"%"),len(txt.ljust(20,"%")))

Python 6
Python 20
Python%%%%%%%%%%%%%% 20

17. center():
string.center(length, character)
The center() method will center align the string, using a specified character (space is
default) as the fill character.

In [50]: 1 txt = "Python"


2 print(txt,len(txt))
3 txt1 = txt.center(20)
4 print(txt1,len(txt1))
5 print(txt.center(20,"%"),len(txt.center(20,"%")))

Python 6
Python 20
%%%%%%%Python%%%%%%% 20

18. rstrip():
string.rstrip(characters)

The rstrip() method removes any trailing characters (characters at the end a string), space
is the default trailing character to remove.

In [51]: 1 txt = " python "


2 print(txt.rstrip())

python

In [52]: 1 txt = ",,,,,ssaaww.....banana"


2 x = txt.rstrip("an.b")
3 print(x)

,,,,,ssaaww

In [53]: 1 txt = "banana,,,,,ssqqqww....."


2 x = txt.rstrip(",.qsw")
3 print(x)

banana

19. lstrip():
string.lstrip(characters)

The lstrip() method removes any leading characters (space is the default leading character
to remove)
In [55]: 1 txt = " python "
2 print(txt.lstrip())

python

In [60]: 1 txt = ",,,,,ssaaww.....banana"


2 x = txt.lstrip(",.as")
3 print(x)

ww.....banana

In [59]: 1 txt = ",,,,,ssaaww.....banana"


2 x = txt.lstrip(",.asw")
3 print(x)

banana

20. strip():
string.strip(characters)

The strip() method removes any leading, and trailing whitespaces.


Leading means at the beginning of the string, trailing means at the end.
You can specify which character(s) to remove, if not, any whitespaces will be removed.

In [61]: 1 txt = " banana "


2 print(txt.strip())

banana

In [62]: 1 txt = ",,,,,rrttgg.....banana....rrr"


2 x = txt.strip(",.grt")
3 print(x)

banana

In [63]: 1 txt = ",,,,,rrttgg.....banana....rrr"


2 x = txt.strip(",.rt")
3 print(x)

gg.....banana

21. replace():
string.replace(oldvalue, newvalue, count)

It returns a copy of the string in which the occurrences of old have been replaced with
new, optionally restricting the number of replacements to max.
All occurrences of the specified phrase will be replaced, if nothing else is specified.

In [65]: 1 s = "I like coding"


2 print(s.replace('coding',"Gaming"))

I like Gaming

In [66]: 1 #Replace all occurrence of the word "one":


2 txt = "one one was a race horse, two two was one too."
3 x = txt.replace("one", "three")
4 print(x)

three three was a race horse, two two was three too.

In [67]: 1 #Replace the two first occurrence of the word "one":


2 txt = "one one was a race horse, two two was one too."
3 x = txt.replace("one", "three", 2)
4 print(x)

three three was a race horse, two two was one too.

In [68]: 1 #If given sub-string not found then it will provide old string as output
2 s = "I like coding"
3 print(s.replace('C',"Gaming"))

I like coding

22. split():
string.split(separator, maxsplit)

separator : Optional. Specifies the separator to use when splitting the string. By default any
whitespace is a separator
maxsplit : Optional. Specifies how many splits to do. Default value is -1, which is "all
occurrences"

The split() method splits a string into a list.


You can specify the separator, default separator is any whitespace.
Note: When maxsplit is specified, the list will contain the specified number of elements
plus one.

In [70]: 1 txt = "welcome to the jungle"


2 x = txt.split()
3 print(x)

['welcome', 'to', 'the', 'jungle']


In [81]: 1 #Split the string, using comma, followed by a space, as a separator:
2 txt = "hello, my name is Peter, I am 26 years old"
3 x = txt.split(", ")
4 print(x)

['hello', 'my name is Peter', 'I am 26 years old']

In [72]: 1 #Use a hash character as a separator:


2 txt = "apple#banana#cherry#orange"
3 x = txt.split("#")
4 print(x)

['apple', 'banana', 'cherry', 'orange']

In [73]: 1 #Split the string into a list with max 2 items:


2 txt = "apple#banana#cherry#orange"
3 # setting the maxsplit parameter to 1, will return a list with 2 elements
4 x = txt.split("#", 1)
5 print(x)

['apple', 'banana#cherry#orange']

23. rsplit():
string.rsplit(separator, maxsplit)

separator : Optional. Specifies the separator to use when splitting the string. By default any
whitespace is a separator
maxsplit : Optional. Specifies how many splits to do. Default value is -1, which is "all
occurrences"

The rsplit() method splits a string into a list, starting from the right.
If no "max" is specified, this method will return the same as the split() method.
Note: When maxsplit is specified, the list will contain the specified number of elements
plus one.

In [74]: 1 txt = "apple, banana, cherry"


2 x = txt.rsplit(", ")
3 print(x)

['apple', 'banana', 'cherry']

In [75]: 1 txt = "welcome to the jungle"


2 x = txt.rsplit()
3 print(x)

['welcome', 'to', 'the', 'jungle']


In [82]: 1 #Split the string, using comma, followed by a space, as a separator:
2 txt = "hello, my name is Peter, I am 26 years old"
3 x = txt.rsplit(", ")
4 print(x)

['hello', 'my name is Peter', 'I am 26 years old']

In [77]: 1 #Split the string into a list with maximum 2 items:


2 txt = "apple, banana, cherry"
3 # setting the maxsplit parameter to 1, will return a list with 2 elements
4 x = txt.rsplit(", ", 1)
5 print(x)

['apple, banana', 'cherry']

24. splitlines():
string.splitlines(keeplinebreaks)

keeplinebreaks : Optional. Specifies if the line breaks should be included (True), or not (False).
Default value is False

The splitlines() method splits a string into a list. The splitting is done at line breaks.

In [83]: 1 txt = "Thank you for the music\nWelcome to the jungle"


2 x = txt.splitlines()
3 print(x)

['Thank you for the music', 'Welcome to the jungle']

In [84]: 1 #Split the string, but keep the line breaks:


2 txt = "Thank you for the music\nWelcome to the jungle"
3 x = txt.splitlines(True)
4 print(x)

['Thank you for the music\n', 'Welcome to the jungle']

25. title():
The title() method returns a string where the first character in every word is upper case.
Like a header, or a title.
If the word contains a number or a symbol, the first letter after that will be converted to
upper case.
In [88]: 1 # Make the first letter in each word upper case:
2 txt = "Welcome to my 2nd world"
3 print(txt.title())

Welcome To My 2Nd World

Note that the first letter after a non-alphabet letter is converted into a upper case letter:

In [89]: 1 txt = "hello b2b2b2 and 3g3g3g"


2 print(txt.title())

Hello B2B2B2 And 3G3G3G

26. zfill():
string.zfill(len)

The zfill() method adds zeros (0) at the beginning of the string, until it reaches the
specified length.
If the value of the len parameter is less than the length of the string, no filling is done.

In [90]: 1 txt1 = "Python is prg lang"


2 txt2 = "Hello"
3 txt3 = "8888"
4 print(txt1.zfill(10))
5 print(txt2.zfill(10))
6 print(txt3.zfill(10))

Python is prg lang


00000Hello
0000008888

27. swapcase():
The swapcase() method returns a string where all the upper case letters are lower case
and vice versa.

In [92]: 1 txt = "Hello My Name Is PETER"


2 print(txt.swapcase())

hELLO mY nAME iS peter

28. isalnum():
The isalnum() method returns True if all the characters are alphanumeric, meaning
alphabet letter (a-z) and numbers (0-9).
Example of characters that are not alphanumeric: (space)!#%&? etc.
In [93]: 1 txt = "Python3"
2 print(txt.isalnum())

True

In [95]: 1 txt = "Python3.9"


2 print(txt.isalnum())

False

In [96]: 1 txt = "Python3 9"


2 print(txt.isalnum())

False

29. isalpha():
The isalpha() method returns True if all the characters are alphabet letters (a-z).
Example of characters that are not alphabet letters: (space)!#%&? etc.

In [98]: 1 txt = "CompanyX"


2 x = txt.isalpha()
3 print(x)

True

In [99]: 1 txt = "Company10"


2 x = txt.isalpha()
3 print(x)

False

30. isascii():
The isascii() method returns True if all the characters are ascii characters (a-z).

In [100]: 1 txt = "Company123"


2 x = txt.isascii()
3 print(x)

True
In [102]: 1 txt = "అమ్మ "
2 x = txt.isascii()
3 print(x)

False

In [103]: 1 txt = "Company123అ"


2 x = txt.isascii()
3 print(x)

False

ASCII Character Set


ASCII stands for the "American Standard Code for Information Interchange".
It was designed in the early 60's, as a standard character set for computers and electronic
devices.
ASCII is a 7-bit character set containing 128 characters.
It contains the numbers from 0-9, the upper and lower case English letters from A to Z,
and some special characters.
The character sets used in modern computers, in HTML, and on the Internet, are all based
on ASCII.
The following tables list the 128 ASCII characters and their equivalent number.

Reference:https://www.w3schools.com/charsets/ref_html_ascii.asp
(https://www.w3schools.com/charsets/ref_html_ascii.asp)

Char Number Description

NUL 0 null character

SOH 1 start of header

STX 2 start of text

ETX 3 end of text

EOT 4 end of transmission

ENQ 5 enquiry

ACK 6 acknowledge

BEL 7 bell (ring)

BS 8 backspace

HT 9 horizontal tab

LF 10 line feed

VT 11 vertical tab

FF 12 form feed

CR 13 carriage return

SO 14 shift out

SI 15 shift in
Char Number Description

DLE 16 data link escape

DC1 17 device control 1

DC2 18 device control 2

DC3 19 device control 3

DC4 20 device control 4

NAK 21 negative acknowledge

SYN 22 synchronize

ETB 23 end transmission block

CAN 24 cancel

EM 25 end of medium

SUB 26 substitute

ESC 27 escape

FS 28 file separator

GS 29 group separator

RS 30 record separator

US 31 unit separator

32 space

! 33 exclamation mark

" 34 quotation mark

# 35 number sign

$ 36 dollar sign

% 37 percent sign

& 38 ampersand

' 39 apostrophe

( 40 left parenthesis

) 41 right parenthesis

* 42 asterisk

+ 43 plus sign

, 44 comma

- 45 hyphen

. 46 period

/ 47 slash

0 48 digit 0

1 49 digit 1

2 50 digit 2

3 51 digit 3
Char Number Description

4 52 digit 4

5 53 digit 5

6 54 digit 6

7 55 digit 7

8 56 digit 8

9 57 digit 9

: 58 colon

; 59 semicolon

< 60 less-than

= 61 equals-to

> 62 greater-than

? 63 question mark

@ 64 at sign

A 65 uppercase A

B 66 uppercase B

C 67 uppercase C

D 68 uppercase D

E 69 uppercase E

F 70 uppercase F

G 71 uppercase G

H 72 uppercase H

I 73 uppercase I

J 74 uppercase J

K 75 uppercase K

L 76 uppercase L

M 77 uppercase M

N 78 uppercase N

O 79 uppercase O

P 80 uppercase P

Q 81 uppercase Q

R 82 uppercase R

S 83 uppercase S

T 84 uppercase T

U 85 uppercase U

V 86 uppercase V

W 87 uppercase W
Char Number Description

X 88 uppercase X

Y 89 uppercase Y

Z 90 uppercase Z

[ 91 left square bracket

\ 92 backslash

] 93 right square bracket

^ 94 caret

_ 95 underscore

` 96 grave accent

a 97 lowercase a

b 98 lowercase b

c 99 lowercase c

d 100 lowercase d

e 101 lowercase e

f 102 lowercase f

g 103 lowercase g

h 104 lowercase h

i 105 lowercase i

j 106 lowercase j

k 107 lowercase k

l 108 lowercase l

m 109 lowercase m

n 110 lowercase n

o 111 lowercase o

p 112 lowercase p

q 113 lowercase q

r 114 lowercase r

s 115 lowercase s

t 116 lowercase t

u 117 lowercase u

v 118 lowercase v

w 119 lowercase w

x 120 lowercase x

y 121 lowercase y

z 122 lowercase z
31. isdecimal():
The isdecimal() method returns True if all the characters are decimals (0-9).
This method can also be used on unicode objects. See example below.

In [105]: 1 txt = "1234"


2 x = txt.isdecimal()
3 print(x)

True

In [114]: 1 #Check if all the characters in the unicode are decimals:


2 ​
3 a = "\u0030" #unicode for 0
4 b = "\u0047" #unicode for G
5 c = "\u0061" ##unicode for a
6 print(a.isdecimal())
7 print(b.isdecimal())
8 print(c.isdecimal())

True
False
False

32. isdigit():
The isdigit() method returns True if all the characters are digits, otherwise False.
Exponents, like ², are also considered to be a digit.

In [115]: 1 s="PYTHON"
2 print(s.isdigit())

False

In [116]: 1 s="12345"
2 print(s.isdigit())

True

In [117]: 1 # even space also it give false


2 s="123 45"
3 print(s.isdigit())

False
In [118]: 1 s="25 is my age"
2 print(s.isdigit())

False

33. isidentifier():
The isidentifier() method returns True if the string is a valid identifier, otherwise False.
A string is considered a valid identifier if it only contains alphanumeric letters (a-z) and (0-
9), or underscores (_). A valid identifier cannot start with a number, or contain any spaces.

In [119]: 1 txt = "Demo"


2 x = txt.isidentifier()
3 print(x)

True

In [122]: 1 txt = "Demo@"


2 x = txt.isidentifier()
3 print(x)

False

In [121]: 1 a = "MyFolder"
2 b = "Demo002"
3 c = "2bring"
4 d = "my demo"
5 ​
6 print(a.isidentifier())
7 print(b.isidentifier())
8 print(c.isidentifier())
9 print(d.isidentifier())

True
True
False
False

34. islower():
Return true if all charcters are in string is lower case,otherwise False.

In [123]: 1 s = "PYTHON"
2 print(s.islower())

False
In [124]: 1 s = "Python"
2 print(s.islower())

False

In [125]: 1 s = "python"
2 print(s.islower())

True

In [126]: 1 s = "python123"
2 print(s.islower())

True

In [127]: 1 s = "python 123"


2 print(s.islower())

True

In [128]: 1 s = "python@"
2 print(s.islower())

True

35. isupper():
Return true if all charcters are in string is upper case,otherwise False.
Numbers, symbols and spaces are not checked, only alphabet characters.

In [129]: 1 s = "PYTHON"
2 print(s.isupper())

True

In [130]: 1 s = "pYTHON"
2 print(s.isupper())

False

In [131]: 1 s = "PYTHON123"
2 print(s.isupper())

True
In [132]: 1 s = "PYTHON123%"
2 print(s.isupper())

True

36. isspace():
The isspace() method returns True if all the characters in a string are whitespaces,
otherwise False.

In [133]: 1 txt = " "


2 x = txt.isspace()
3 print(x)

True

In [134]: 1 txt = ""


2 x = txt.isspace()
3 print(x)

False

In [135]: 1 txt = " "


2 x = txt.isspace()
3 print(x)

True

In [136]: 1 txt = " python "


2 x = txt.isspace()
3 print(x)

False

In [137]: 1 PyStr="\t\t"
2 print(PyStr.isspace())
3 PyStr="\n"
4 print(PyStr.isspace())

True
True

37. isprintable():
The isprintable() method returns True if all the characters are printable, otherwise False.
Example of none printable character can be carriage return and line feed.
In [138]: 1 txt = "Hello! Are you #1?"
2 x = txt.isprintable()
3 print(x)

True

In [139]: 1 txt = "Hello!\nAre you #1?"


2 x = txt.isprintable()
3 print(x)

False

In [140]: 1 txt = "Hello! \t Are you #1?"


2 x = txt.isprintable()
3 print(x)

False

38. isnumeric():
The isnumeric() method returns True if all the characters are numeric (0-9), otherwise
False.
Exponents, like ² and ¾ are also considered to be numeric values.
"-1" and "1.5" are NOT considered numeric values, because all the characters in the string
must be numeric, and the - and the . are not.

In [141]: 1 txt = "565543"


2 x = txt.isnumeric()
3 print(x)

True

In [142]: 1 a = "\u0030" #unicode for 0


2 b = "\u00B2" #unicode for &sup2;
3 c = "10km2"
4 d = "-1"
5 e = "1.5"
6 ​
7 print(a.isnumeric())
8 print(b.isnumeric())
9 print(c.isnumeric())
10 print(d.isnumeric())
11 print(e.isnumeric())

True
True
False
False
False
39. istitle():
The istitle() method returns True if all words in a text start with a upper case letter, AND
the rest of the word are lower case letters, otherwise False.
Symbols and numbers are ignored.

In [143]: 1 txt = "Hello, And Welcome To My World!"


2 x = txt.istitle()
3 print(x)

True

In [144]: 1 a = "HELLO, AND WELCOME TO MY WORLD"


2 b = "Hello"
3 c = "22 Names"
4 d = "This Is %'!?"
5 ​
6 print(a.istitle())
7 print(b.istitle())
8 print(c.istitle())
9 print(d.istitle())

False
True
True
True

40. maketrans():
str.maketrans(x, y, z)

x :
Required. If only one parameter is specified, this has to be a dictio
nary describing how to perform the replace. If two or more parameters
are specified, this parameter has to be a string specifying the chara
cters you want to replace.<br>
y :
Optional. A string with the same length as parameter x. Each characte
r in the first parameter will be replaced with the corresponding char
acter in this string.<br>
z :
Optional. A string describing which characters to remove from the ori
ginal string.

The maketrans() method returns a mapping table that can be used with the translate()
method to replace specified characters.
In [159]: 1 #Create a mapping table, and use it in the translate() method to replace
2 ​
3 txt = "Hello Sam!"
4 mytable = txt.maketrans("S", "P")
5 print(txt.translate(mytable))

Hello Pam!

In [160]: 1 #Use a mapping table to replace many characters:


2 ​
3 txt = "Hi Sam!"
4 x = "mSa"
5 y = "eJo"
6 mytable = txt.maketrans(x, y)
7 print(txt.translate(mytable))

Hi Joe!

In [161]: 1 txt = "Hi Sam!"


2 x = "Sma"
3 y = "eJo"
4 mytable = txt.maketrans(x, y)
5 print(txt.translate(mytable))

Hi eoJ!

In [162]: 1 txt = "Hi Sam!"


2 x = "Sma"
3 y = "eJo0"
4 mytable = txt.maketrans(x, y)
5 print(txt.translate(mytable))

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [162], in <cell line: 4>()
2 x = "Sma"
3 y = "eJo0"
----> 4 mytable = txt.maketrans(x, y)
5 print(txt.translate(mytable))

ValueError: the first two maketrans arguments must have equal length
In [164]: 1 #The third parameter in the mapping table describes characters that you w
2 ​
3 txt = "Good night Sam!"
4 x = "mSa"
5 y = "eJo"
6 z = "odnght"
7 mytable = txt.maketrans(x, y, z)
8 print(txt.translate(mytable))

G i Joe!

In [165]: 1 txt = "Good night Samnnnnnnnnnn!"


2 x = "mSa"
3 y = "eJo"
4 z = "odnght"
5 mytable = txt.maketrans(x, y, z)
6 print(txt.translate(mytable))

G i Joe!

In [166]: 1 #The maketrans() method itself returns a dictionary describing each repla
2 ​
3 txt = "Good night Sam!"
4 x = "mSa"
5 y = "eJo"
6 z = "odnght"
7 print(txt.maketrans(x, y, z))

{109: 101, 83: 74, 97: 111, 111: None, 100: None, 110: None, 103: None, 104:
None, 116: None}

41. translate():
string.translate(table)

table : Required. Either a dictionary, or a mapping table describing how to perform the replace

The translate() method returns a string where some specified characters are replaced with
the character described in a dictionary, or in a mapping table.
Use the maketrans() method to create a mapping table.
If a character is not specified in the dictionary/table, the character will not be replaced.
If you use a dictionary, you must use ascii codes instead of characters.

In [170]: 1 #use a dictionary with ascii codes to replace 83 (S) with 80 (P):
2 mydict = {83: 80}
3 txt = "Hello Sam!"
4 print(txt.translate(mydict))

Hello Pam!
In [175]: 1 print(chr(83))
2 print(chr(80))

S
P

In [185]: 1 #Use a mapping table to replace "S" with "P":


2 ​
3 txt = "Hello Sam!"
4 mytable = txt.maketrans("S", "P")
5 print(txt.translate(mytable))

Hello Pam!

In [184]: 1 #Use a mapping table to replace many characters:


2 ​
3 txt = "Hi Sam!"
4 x = "mSa"
5 y = "eJo"
6 mytable = txt.maketrans(x, y)
7 print(txt.translate(mytable))

Hi Joe!

In [183]: 1 #The third parameter in the mapping table describes characters that you w
2 ​
3 txt = "Good night Sam!"
4 x = "mSa"
5 y = "eJo"
6 z = "odnght"
7 mytable = txt.maketrans(x, y, z)
8 print(txt.translate(mytable))

G i Joe!

In [182]: 1 txt = "Good night Sam!"


2 x = "mSa"
3 y = "eJo"
4 z = "odnght"
5 print(txt.maketrans(x, y, z))

{109: 101, 83: 74, 97: 111, 111: None, 100: None, 110: None, 103: None, 104:
None, 116: None}

In [181]: 1 #The same example as above, but using a dictionary instead of a mapping t
2 ​
3 txt = "Good night Sam!"
4 mydict = {109: 101, 83: 74, 97: 111, 111: None, 100: None, 110: None, 103
5 print(txt.translate(mydict))

G i Joe!
42. partition():
string.partition(value)

value : Required. The string to search for

The partition() method searches for a specified string, and splits the string into a tuple
containing three elements.
The first element contains the part before the specified string.
The second element contains the specified string.
The third element contains the part after the string.
Note: This method searches for the first occurrence of the specified string.

In [188]: 1 # Search for the word "bananas", and return a tuple with three elements:
2 # 1 - everything before the "match"
3 # 2 - the "match"
4 # 3 - everything after the "match"
5 ​
6 txt = "I could eat bananas all day, bananas are my favorite fruit"
7 x = txt.partition("bananas")
8 print(x)

('I could eat ', 'bananas', ' all day, bananas are my favorite fruit')

In [190]: 1 # If the specified value is not found, the partition() method returns a t
2 # 1 - the whole string
3 # 2 - an empty string
4 # 3 - an empty string:
5 ​
6 txt = "I could eat bananas all day, bananas are my favorite fruit"
7 x = txt.partition("apples")
8 print(x)

('I could eat bananas all day, bananas are my favorite fruit', '', '')

43. rpartition():
string.rpartition(value)

value : Required. The string to search for

The rpartition() method searches for the last occurrence of a specified string, and splits the
string into a tuple containing three elements.
The first element contains the part before the specified string.
The second element contains the specified string.
The third element contains the part after the string.
In [189]: 1 # Search for the last occurrence of the word "bananas", and return a tupl
2 ​
3 # 1 - everything before the "match"
4 # 2 - the "match"
5 # 3 - everything after the "match"
6 ​
7 txt = "I could eat bananas all day, bananas are my favorite fruit"
8 x = txt.rpartition("bananas")
9 print(x)

('I could eat bananas all day, ', 'bananas', ' are my favorite fruit')

In [191]: 1 # If the specified value is not found, the rpartition() method returns a
2 # 1 - an empty string
3 # 2 - an empty string
4 # 3 - the whole string:
5 ​
6 txt = "I could eat bananas all day, bananas are my favorite fruit"
7 x = txt.rpartition("apples")
8 print(x)

('', '', 'I could eat bananas all day, bananas are my favorite fruit')

Booleans
Booleans represent one of two values: True or False.
In programming you often need to know if an expression is True or False.
You can evaluate any expression in Python, and get one of two answers, True or False.
When you compare two values, the expression is evaluated and Python returns the
Boolean answer:

In [193]: 1 print(10 > 9)


2 print(10 == 9)
3 print(10 < 9)

True
False
False

When you run a condition in an if statement, Python returns True or False:


In [194]: 1 #Example : Print a message based on whether the condition is True or Fals
2 ​
3 a = 200
4 b = 33
5 ​
6 if b > a:
7 print("b is greater than a")
8 else:
9 print("b is not greater than a")

b is not greater than a

Evaluate Values and Variables


The bool() function allows you to evaluate any value, and give you True or False in return,

In [195]: 1 print(bool("Hello"))
2 print(bool(15))

True
True

In [196]: 1 x = "Hello"
2 y = 15
3 ​
4 print(bool(x))
5 print(bool(y))

True
True

Most Values are True

Almost any value is evaluated to True if it has some sort of content.


Any string is True, except empty strings.
Any number is True, except 0.
Any list, tuple, set, and dictionary are True, except empty ones.

Some Values are False

In fact, there are not many values that evaluate to False, except empty values, such as (), [], {},
"", the number 0, and the value None.
In [198]: 1 # True values
2 print(bool("abc"))
3 print(bool(123))
4 print(bool(["apple", "cherry", "banana"]))

True
True
True

In [201]: 1 # False value


2 print(bool(False))
3 print(bool(None))
4 print(bool(0))
5 print(bool(""))
6 print(bool(()))
7 print(bool([]))
8 print(bool({}))

False
False
False
False
False
False
False

Functions can Return a Boolean

You can create functions that returns a Boolean Value:

In [202]: 1 def myFunction() :


2 return True
3 ​
4 print(myFunction())

True

You can execute code based on the Boolean answer of a function:

In [204]: 1 #Example : Print "YES!" if the function returns True, otherwise print "NO
2 ​
3 def myFunction() :
4 return True
5 ​
6 if myFunction():
7 print("YES!")
8 else:
9 print("NO!")

YES!
Python also has many built-in functions that return a boolean value, like the isinstance()
function, which can be used to determine if an object is of a certain data type:

In [206]: 1 #Example : Check if an object is an integer or not:


2 x = 200
3 print(isinstance(x, int))

True

You might also like