SlideShare a Scribd company logo
1 of 28
Download to read offline
PYTHON APPLICATION PROGRAMMING -18EC646
MODULE 2
STRINGS
Prof. Krishnananda L
Department of ECE
Govt SKSJTI
Bengaluru
STRINGS:
 A string is a group/ a sequence of characters. Since Python has no provision
for arrays, we simply use strings. We use a pair of single or double quotes to
declare a string.
 Strings is “sequence data type” in python: meaning – its ordered, elements
can be accessed using positional index
 String may contain alphabets, numerals, special characters or a combination
of all these.
 String is a sequence of characters represented in Unicode. Each character of
a string corresponds to an index number, starting with zero.
 Strings are “immutable” i.e., once defined, the string literals cannot be
reassigned directly.
 Python supports positive indexing of string starting from the beginning of the
string as well as negative indexing of string starting from the end of the
string .
 Python has a vast library having built-in methods to operate on strings
2
STRING EXAMPLE PROGRAM:
 Example1
 INPUT:
>>> print(‘Hello world’)
 OUTPUT:
Hello world
 INPUT:
>>> print(“Hello world@@”)
 OUTPUT:
Hello world@@
 Example 2
 INPUT:
>>>a = 'Hello world’
>>>print(a)
 OUTPUT:
Hello world
 INPUT:
>>>a = 'Hello world’
>>> a
 OUTPUT:
‘Hello world’
 Example 3
 INPUT:
>>>a = 'Hello world’
>>>a[0]=‘M’
 OUTPUT:
 Traceback (most recent call last):
File "<pyshell#19>", line 1, in
<module>
a[0]='M'
TypeError: 'str' object does not
support item assignment
Note: String is “immutable” Not
possible to change the elements of the
string through assignment operator
3
POSITIVEAND NEGATIVE INDEXING OF A STRING:
 Positive indexing:
 INPUT:
>>>a = ‘Hello world’
print(a[1])
 OUTPUT:
e
 Negative indexing:
 INPUT:
>>> a = 'Hello World’
>>> print(a[-1])
 OUTPUT:
d
>>>a = "Hello, World!"
>>>print(a[7])
W
4
MULTILINE STRINGS:
 using three quotes:
 INPUT:
a = “””Python is an interpreted high-level
general-purpose programming language. Python's
design philosophy emphasizes code readability
with significant indentation.”””
print(a)
 OUTPUT:
Python is an interpreted high-level general-
purpose programming language. Python's design
philosophy emphasizes code readability with
significant indentation.
 Using three single quotes:
 INPUT:
a = ‘’’Python is an interpreted high-level
general-purpose programming language. Python's
design philosophy emphasizes code readability
with significant indentation.’’’
print(a)
 OUTPUT:
Python is an interpreted high-level general-
purpose programming language. Python's design
philosophy emphasizes code readability with
significant indentation. 5
LOOPING THROUGHA STRING:
 For loop:
 INPUT:
for x in “hello":
print(x)
 OUTPUT:
h
e
l
l
o
 While loop:
 INPUT:
st=“hello"
i=0
while i<len(st):
print(st[i], end=‘ ’))
i=i+1
 OUTPUT:
hello
str = "welcome to Python class "
for k in str:
if k == 'P':
break
print(k, end=' ')
Output:
welcome to
str = "welcome to Python class "
for k in str:
print(k, end=' ')
if k == 'P':
break
Output:
welcome to P
6
LOOPING CONTD…
## to print names of the list
print ("illustration of for loop--- printing names
from list")
names=["anand", "arun", "akshata", "anusha"]
for i in names:
print ("hello " , i)
print ("COMPLETED ---")
# prints all letters except 'a' and 'k'
## illustration of continue
## illustration of logical operators
i = 0
str1 = ‘all is well'
while i < len(str1):
if str1[i] == ‘s' or str1[i] == ‘l':
i += 1
continue
print('Current Letter :', str1[i])
i += 1
Current Letter : a
Current Letter :
Current Letter : i
Current Letter :
Current Letter : w
Current Letter : e 7
LOOPING CONTD..
""" program to illustrate for loop and multiple if statements
with string to count the occurrence of each vowel """
txt='HELLO how are you? I am fine'
counta, counte, counti, counto, countu=0,0,0,0,0
for k in txt:
if k=='a' or k=='A':
counta+=1
if k=='e' or k=='E':
counte+=1
if k=='i' or k==‘’I’:
counti+=1
if k=='o' or k =='O':
counto+=1
if k=='u' or k=='U':
countu+=1
print ("Given string is %s " %(txt))
print ("total 'A' or 'a' in the string is: %d " %(counta))
print ("total 'E' or 'e' in the string is: %d " %(counte))
print ("total 'I' or 'i' in the string is: %d " %(counti))
print ("total 'O' or '0' in the string is: %d " %(counto))
print ("total 'U' or 'u' in the string is: %d " %(countu))
Output:
Given string is HELLO how are you? I am fine
total 'A' or 'a' in the string is: 2
total 'E' or 'e' in the string is: 3
total 'I' or 'i' in the string is: 2
total 'O' or '0' in the string is: 3
total 'U' or 'u' in the string is: 1
8
CHECK STRING (PHRASES IN STRINGS):
 Normal:
 INPUT:
txt = ‘happiness is free“
print("free" in txt)
 OUTPUT:
True
 INPUT:
txt = “happiness is free”
print(“hello” in txt)
 OUTPUT:
False
 With if statement:
 INPUT:
txt = “happiness is free”
if “free” in txt:
print("Yes, 'free' is present.")
 OUTPUT:
Yes, 'free' is present.
txt = "The quick brown fox jumps over
the lazy dog!"
if "fox" in txt:
print("Yes, 'fox' is present.")
else:
print ("No, ‘fox’is not present")
## to check for a phrase in a string
>>>txt = "The best things in life are free!"
>>>print(“life" in txt)
True 9
CHECK STRING :
 Normal:
 INPUT:
txt = ‘welcome to python’
print(‘world’ not in txt)
 OUTPUT:
True
 With if statement:
 INPUT:
txt = “welcome to python“
if “hello" not in txt:
print("Yes, ‘hello' is NOT present.")
 OUTPUT:
Yes, ‘hello' is NOT present.
10
STRING LENGTH AND SLICING:
 String length:
 INPUT:
a = "Hello World”
print(len(a))
 OUTPUT:
11
 INPUT:
a = “Welcome to Python programming @@@“
print (len(a))
 OUTPUT:
33
 String slicing:
 INPUT:
b = "Hello World“
print(b[2:5]) ## from index 2 to index4
 OUTPUT:
llo
 INPUT:
b = "Hello World“
print(b[:5]) ## from beginning 5 characters
 OUTPUT:
Hello
11
STRING SLICING METHODS:
 From the Start:
 INPUT:
>>>b = ‘’python is high level
programming language“
>>>print(b[:10])
 OUTPUT:
python is
## consider from the
beginning 10 characters and
print
 Till the End:
 INPUT:
>>>b = "python is high level
programming language“
>>>print(b[10:])
 OUTPUT:
high level programming
language
## skip first 10 characters
from the beginning and print
remaining till end of string
 With Negative indexing
 INPUT:
>>>b = "python is high level
programming language“
>>>print (b[:-5])
OUTPUT:
python is high level programming lan
>>>print (b[-5:])
OUTPUT:
guage 12
STRING SLICING CONTD…
## illustration of slicing
## get a range of characters from the complete string
>>>txt = "Govt SKSJTI Bengaluru"
# print characters in position 5 to 10. (position 11 not
included)
>>>print(txt[5:11])
SKSJTI
## slicing from the beginning without initial index
>>>txt = "Govt SKSJTI Bengaluru"
>>>print(txt[:4]) # from start to position 3
Govt
### slicing till the end without last index
>>>txt = "Govt SKSJTI Bengaluru"
>>>print(txt[7:]) ## from position 7 to last character
SJTI Bengaluru
### Negative indexing
>>>txt = "Govt SKSJTI Bengaluru"
>>> print(txt[-16:-8]) ## position -8 not
included
SKSJTI B
>>>txt = "Govt SKSJTI Bengaluru"
>>> print(txt[:-16])
Govt
>>>txt = "Govt SKSJTI Bengaluru"
>>> print(txt[-9:])
Bengaluru 13
BUILT-IN STRING METHODS IN PYTHON:
 Upper case:
 INPUT:
>>> a = "Hello World”
>>>print(a.upper())
 OUTPUT:
HELLO WORLD
 Lower case:
 INPUT:
a = "Hello World“
print(a.lower())
 OUTPUT:
hello world
 capitalize:
 INPUT:
>>>a = “hello world”
>>> print(a.capitalize())
 OUTPUT:
Hello world
 Misc:
 INPUT:
>>>a = “hello world”
>>> print(a.islower())
 OUTPUT:
True
>>>a = “hello world”
>>> print(a.isupper())
 OUTPUT:
False
Note:String methods do not modify the original string.
14
BUILT-IN STRING METHODS IN PYTHON
 Remove Whitespace(strip):
 INPUT:
>>> a = " Hello World "
>>>print(a.strip())
 OUTPUT:
Hello World
## remove white spaces at the
beginning and end of the string
>>> a = " our first python prog"
>>>print(a.lstrip(‘our’))
OUTPUT:
first python prog
 Splitting string:
 INPUT:
>>> a = " hello and welcome”
>>>print(a.split())
 OUTPUT:
['hello', 'and', 'welcome']
#list with 3 elements
>>>a = " hello,how,are,you”
>>>print(a.split())
 OUTPUT:
['hello,how,are,you']
## list with single element
 INPUT:
>>>a = " hello,how,are,you”
>>>print(a.split(‘,’))
 OUTPUT:
['hello', 'how', 'are', 'you']
## list with 4 elements
## splits the string at the specified
separator and returns a list. Default
separator white space
>>>a = “but put cut”
>>>print(a.split(‘t’))
 OUTPUT:
['bu', ' pu', ' cu', '']
15
 Count occurrence:
 INPUT:
a = "Hello World“
print(a.count(‘l’)
 OUTPUT:
3
 To find position
(index):
 INPUT:
>>>a = “Hello world”
>>> print(a.indix(‘w’))
OUTPUT:
6
BUILT-IN STRING METHODS IN PYTHON
 Check for digits:
 INPUT:
a = "Hello 23“
print(a.isdigit())
 OUTPUT:
False
a = “2345’
print(a.isdigit())
 OUTPUT:
True
 Check for alphabets:
 INPUT:
a = "Hello 23”
print(a.isalpha())
 OUTPUT:
False
>>>a = “hello "
>>>print(a.isaplpha())
 OUTPUT:
False
a = “hello" print(a.isaplpha())
 OUTPUT:
False
16
 Concatenation:
 INPUT:
a = "Hello“
b = "World“
c = a + b
d = a + “, " + b
print(c)
print(d)
 OUTPUT:
HelloWorld
Hello,World
BUILT-IN STRING METHODS IN PYTHON
Replace a character or string:
INPUT:
>>>a = “Geeks for Geeks“
print(a.replace(‘G’, ‘W’))
OUTPUT:
Weeks for Weeks
INPUT:
a = “Hello welcome to Python“
print(a.replace(‘Hello’, ‘Krishna’)
OUTPUT:
Krishna welcome to Python
17
LOOPING TO COUNT:
 INPUT:
word='python program’
count=0
for letter in word:
if letter=='p’:
count=count+1
print(count)
 OUTPUT:
2
 INPUT:
s = "peanut butter“
count = 0
for char in s:
if char == "t":
count = count + 1
print(count)
 OUTPUT:
3
18
PARSINGAND FORMAT STRINGS:
 Parsing:
 INPUT:
st="From mamatha.a@gmail.com"
pos=st.find('@’)
print('Position of @ is', pos)
 OUTPUT:
Position of @ is 14
 Format:
 INPUT:
print ('My name is %s and age is %d ’% (‘Arun', 21))
 OUTPUT:
My name is Arun and age is 21
19
STRING FORMATTING
 Without built in function:
 INPUT:
age = 36
print( "My name is John, I am ", + age)
 OUTPUT:
My name is John,I am 36
 With built in function:
 INPUT:
age = 36
print( "My name is John, I am {} ".format(age))
 OUTPUT:
My name is John, I am 36
20
MULTIPLE PLACE HOLDERS IN STRING FORMAT
 Without index numbers:
 INPUT:
quantity = 3
itemno = 5
price = 49.95
myorder = “I want {} pieces of item {} for {}
dollars.“
print(myorder.format(quantity, itemno, price))
 OUTPUT:
I want 3 pieces of item 5 for 49.95 dollars.
 With index numbers:
 INPUT:
quantity = 3
itemno = 5
price = 49.95
myorder = "I want to pay {2} dollars for {0}
pieces of item {1}.“
print(myorder.format(quantity, itemno, price))
 OUTPUT:
I want to pay 49.95 dollars for 3 pieces of item 5.
21
ESCAPE SEQUENCES
 To insert characters that are illegal in a string, we use an
escape character.
 Example:
 INPUT:
txt = "We are the so-called "Vikings" from the north."
print(txt)
 OUTPUT:
We are the so-called "Vikings" from the north.
22
23
STRING COMPARISON:
 Normal:
 INPUT:
>>> print(‘python’==‘python’)
>>> print(’Python’< ‘python’)
>>> print (’PYTHON’==‘python’)
 OUTPUT:
True
True
False
.
 Using is operator:
 >>>str1=‘python’
 >>>str2=‘Python’
 >>>str3=str1
 >>> str1 is str2
False
>>> str3 is str1
True
>>> str2 is not str1
True
>>>str1+=‘s’
>>> id(str1)
1918301558320
>>> id(str2)
1918291321200
>>> id(str3)
1918301558320
>>>id(str1)
1918301822256
The relational operators compare
the Unicode values of the characters
of the strings from the zeroth index
till the end of the string. It then
returns a boolean value according to
the result of value comparison
is and is not operators check
whether both the operands
refer to the same object or
not. If object ids are same, it
returns True
24
STRING SPECIAL OPERATORS:
25
SUMMARY OF BUILT-IN 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
find() Searches the string for a specified value and
returns the position of where it was found
format() Formats specified values in a string
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
isdecimal() Returns True if all characters in the string are
decimals
26
CONTD..
isdigit() Returns True if all characters in the string
are digits
isidentifi
er()
Returns True if the string is an identifier
islower() Returns True if all characters in the string
are lower case
isnumeri
c()
Returns True if all characters in the string
are numeric
isprintab
le()
Returns True if all characters in the string
are printable
isspace() Returns True if all characters in the string
are whitespaces
istitle() Returns True if the string follows the
isupper() ReturnsTrue if all characters in the
string are uppercase
join() Joins the elements of an iterable to the end
of the 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
27
CONTD..
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
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 returnsa list
rstrip() Returns a right trim version of the
string
split() Splits the string at the specified
separator, and returnsa 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
28

More Related Content

What's hot

An introduction to Python for absolute beginners
An introduction to Python for absolute beginnersAn introduction to Python for absolute beginners
An introduction to Python for absolute beginnersKálmán "KAMI" Szalai
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Paige Bailey
 
Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python Jaganadh Gopinadhan
 
String in python use of split method
String in python use of split methodString in python use of split method
String in python use of split methodvikram mahendra
 
Python language data types
Python language data typesPython language data types
Python language data typesHoang Nguyen
 
Python and sysadmin I
Python and sysadmin IPython and sysadmin I
Python and sysadmin IGuixing Bai
 
Programming Under Linux In Python
Programming Under Linux In PythonProgramming Under Linux In Python
Programming Under Linux In PythonMarwan Osman
 
Programming in Python
Programming in Python Programming in Python
Programming in Python Tiji Thomas
 
Learn python in 20 minutes
Learn python in 20 minutesLearn python in 20 minutes
Learn python in 20 minutesSidharth Nadhan
 
Introduction to Python and TensorFlow
Introduction to Python and TensorFlowIntroduction to Python and TensorFlow
Introduction to Python and TensorFlowBayu Aldi Yansyah
 
Introduction to advanced python
Introduction to advanced pythonIntroduction to advanced python
Introduction to advanced pythonCharles-Axel Dein
 
Strings in Python
Strings in PythonStrings in Python
Strings in Pythonnitamhaske
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Paige Bailey
 
FUNDAMENTALS OF PYTHON LANGUAGE
 FUNDAMENTALS OF PYTHON LANGUAGE  FUNDAMENTALS OF PYTHON LANGUAGE
FUNDAMENTALS OF PYTHON LANGUAGE Saraswathi Murugan
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayUtkarsh Sengar
 

What's hot (20)

Python basics
Python basicsPython basics
Python basics
 
Python for Beginners(v1)
Python for Beginners(v1)Python for Beginners(v1)
Python for Beginners(v1)
 
An introduction to Python for absolute beginners
An introduction to Python for absolute beginnersAn introduction to Python for absolute beginners
An introduction to Python for absolute beginners
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!
 
Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python
 
String in python use of split method
String in python use of split methodString in python use of split method
String in python use of split method
 
Python basic
Python basicPython basic
Python basic
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python and sysadmin I
Python and sysadmin IPython and sysadmin I
Python and sysadmin I
 
python.ppt
python.pptpython.ppt
python.ppt
 
Programming Under Linux In Python
Programming Under Linux In PythonProgramming Under Linux In Python
Programming Under Linux In Python
 
Programming in Python
Programming in Python Programming in Python
Programming in Python
 
Learn python in 20 minutes
Learn python in 20 minutesLearn python in 20 minutes
Learn python in 20 minutes
 
Introduction to Python and TensorFlow
Introduction to Python and TensorFlowIntroduction to Python and TensorFlow
Introduction to Python and TensorFlow
 
Introduction to advanced python
Introduction to advanced pythonIntroduction to advanced python
Introduction to advanced python
 
Strings in Python
Strings in PythonStrings in Python
Strings in Python
 
Pythonppt28 11-18
Pythonppt28 11-18Pythonppt28 11-18
Pythonppt28 11-18
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)
 
FUNDAMENTALS OF PYTHON LANGUAGE
 FUNDAMENTALS OF PYTHON LANGUAGE  FUNDAMENTALS OF PYTHON LANGUAGE
FUNDAMENTALS OF PYTHON LANGUAGE
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 

Similar to Python- strings

Similar to Python- strings (20)

Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
 
Introduction To Python
Introduction To  PythonIntroduction To  Python
Introduction To Python
 
Strings in python
Strings in pythonStrings in python
Strings in python
 
stringsinpython-181122100212.pdf
stringsinpython-181122100212.pdfstringsinpython-181122100212.pdf
stringsinpython-181122100212.pdf
 
Core Concept_Python.pptx
Core Concept_Python.pptxCore Concept_Python.pptx
Core Concept_Python.pptx
 
UNIT 4 python.pptx
UNIT 4 python.pptxUNIT 4 python.pptx
UNIT 4 python.pptx
 
MODULE. .pptx
MODULE.                              .pptxMODULE.                              .pptx
MODULE. .pptx
 
gdscpython.pdf
gdscpython.pdfgdscpython.pdf
gdscpython.pdf
 
Python ppt
Python pptPython ppt
Python ppt
 
Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )
 
Introduction to Python for Bioinformatics
Introduction to Python for BioinformaticsIntroduction to Python for Bioinformatics
Introduction to Python for Bioinformatics
 
Python slide.1
Python slide.1Python slide.1
Python slide.1
 
Python data handling
Python data handlingPython data handling
Python data handling
 
Python Strings.pptx
Python Strings.pptxPython Strings.pptx
Python Strings.pptx
 
05 c++-strings
05 c++-strings05 c++-strings
05 c++-strings
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
Python 3.pptx
Python 3.pptxPython 3.pptx
Python 3.pptx
 
Python basics
Python basicsPython basics
Python basics
 
STRINGS_IN_PYTHON 9-12 (1).pptx
STRINGS_IN_PYTHON 9-12 (1).pptxSTRINGS_IN_PYTHON 9-12 (1).pptx
STRINGS_IN_PYTHON 9-12 (1).pptx
 
Python programming
Python  programmingPython  programming
Python programming
 

More from Krishna Nanda

Python regular expressions
Python regular expressionsPython regular expressions
Python regular expressionsKrishna Nanda
 
Computer Communication Networks- Introduction to Transport layer
Computer Communication Networks- Introduction to Transport layerComputer Communication Networks- Introduction to Transport layer
Computer Communication Networks- Introduction to Transport layerKrishna Nanda
 
Computer Communication Networks- TRANSPORT LAYER PROTOCOLS
Computer Communication Networks- TRANSPORT LAYER PROTOCOLSComputer Communication Networks- TRANSPORT LAYER PROTOCOLS
Computer Communication Networks- TRANSPORT LAYER PROTOCOLSKrishna Nanda
 
COMPUTER COMMUNICATION NETWORKS -IPv4
COMPUTER COMMUNICATION NETWORKS -IPv4COMPUTER COMMUNICATION NETWORKS -IPv4
COMPUTER COMMUNICATION NETWORKS -IPv4Krishna Nanda
 
COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2
COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2
COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2Krishna Nanda
 
Computer Communication Networks-Routing protocols 1
Computer Communication Networks-Routing protocols 1Computer Communication Networks-Routing protocols 1
Computer Communication Networks-Routing protocols 1Krishna Nanda
 
Computer Communication Networks-Wireless LAN
Computer Communication Networks-Wireless LANComputer Communication Networks-Wireless LAN
Computer Communication Networks-Wireless LANKrishna Nanda
 
Computer Communication Networks-Network Layer
Computer Communication Networks-Network LayerComputer Communication Networks-Network Layer
Computer Communication Networks-Network LayerKrishna Nanda
 
Lk module4 structures
Lk module4 structuresLk module4 structures
Lk module4 structuresKrishna Nanda
 

More from Krishna Nanda (16)

Python regular expressions
Python regular expressionsPython regular expressions
Python regular expressions
 
Python dictionaries
Python dictionariesPython dictionaries
Python dictionaries
 
Python lists
Python listsPython lists
Python lists
 
Python-Tuples
Python-TuplesPython-Tuples
Python-Tuples
 
Python-files
Python-filesPython-files
Python-files
 
Computer Communication Networks- Introduction to Transport layer
Computer Communication Networks- Introduction to Transport layerComputer Communication Networks- Introduction to Transport layer
Computer Communication Networks- Introduction to Transport layer
 
Computer Communication Networks- TRANSPORT LAYER PROTOCOLS
Computer Communication Networks- TRANSPORT LAYER PROTOCOLSComputer Communication Networks- TRANSPORT LAYER PROTOCOLS
Computer Communication Networks- TRANSPORT LAYER PROTOCOLS
 
COMPUTER COMMUNICATION NETWORKS -IPv4
COMPUTER COMMUNICATION NETWORKS -IPv4COMPUTER COMMUNICATION NETWORKS -IPv4
COMPUTER COMMUNICATION NETWORKS -IPv4
 
COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2
COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2
COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2
 
Computer Communication Networks-Routing protocols 1
Computer Communication Networks-Routing protocols 1Computer Communication Networks-Routing protocols 1
Computer Communication Networks-Routing protocols 1
 
Computer Communication Networks-Wireless LAN
Computer Communication Networks-Wireless LANComputer Communication Networks-Wireless LAN
Computer Communication Networks-Wireless LAN
 
Computer Communication Networks-Network Layer
Computer Communication Networks-Network LayerComputer Communication Networks-Network Layer
Computer Communication Networks-Network Layer
 
Lk module3
Lk module3Lk module3
Lk module3
 
Lk module4 structures
Lk module4 structuresLk module4 structures
Lk module4 structures
 
Lk module4 file
Lk module4 fileLk module4 file
Lk module4 file
 
Lk module5 pointers
Lk module5 pointersLk module5 pointers
Lk module5 pointers
 

Recently uploaded

Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and usesDevarapalliHaritha
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2RajaP95
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 

Recently uploaded (20)

Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and uses
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 

Python- strings

  • 1. PYTHON APPLICATION PROGRAMMING -18EC646 MODULE 2 STRINGS Prof. Krishnananda L Department of ECE Govt SKSJTI Bengaluru
  • 2. STRINGS:  A string is a group/ a sequence of characters. Since Python has no provision for arrays, we simply use strings. We use a pair of single or double quotes to declare a string.  Strings is “sequence data type” in python: meaning – its ordered, elements can be accessed using positional index  String may contain alphabets, numerals, special characters or a combination of all these.  String is a sequence of characters represented in Unicode. Each character of a string corresponds to an index number, starting with zero.  Strings are “immutable” i.e., once defined, the string literals cannot be reassigned directly.  Python supports positive indexing of string starting from the beginning of the string as well as negative indexing of string starting from the end of the string .  Python has a vast library having built-in methods to operate on strings 2
  • 3. STRING EXAMPLE PROGRAM:  Example1  INPUT: >>> print(‘Hello world’)  OUTPUT: Hello world  INPUT: >>> print(“Hello world@@”)  OUTPUT: Hello world@@  Example 2  INPUT: >>>a = 'Hello world’ >>>print(a)  OUTPUT: Hello world  INPUT: >>>a = 'Hello world’ >>> a  OUTPUT: ‘Hello world’  Example 3  INPUT: >>>a = 'Hello world’ >>>a[0]=‘M’  OUTPUT:  Traceback (most recent call last): File "<pyshell#19>", line 1, in <module> a[0]='M' TypeError: 'str' object does not support item assignment Note: String is “immutable” Not possible to change the elements of the string through assignment operator 3
  • 4. POSITIVEAND NEGATIVE INDEXING OF A STRING:  Positive indexing:  INPUT: >>>a = ‘Hello world’ print(a[1])  OUTPUT: e  Negative indexing:  INPUT: >>> a = 'Hello World’ >>> print(a[-1])  OUTPUT: d >>>a = "Hello, World!" >>>print(a[7]) W 4
  • 5. MULTILINE STRINGS:  using three quotes:  INPUT: a = “””Python is an interpreted high-level general-purpose programming language. Python's design philosophy emphasizes code readability with significant indentation.””” print(a)  OUTPUT: Python is an interpreted high-level general- purpose programming language. Python's design philosophy emphasizes code readability with significant indentation.  Using three single quotes:  INPUT: a = ‘’’Python is an interpreted high-level general-purpose programming language. Python's design philosophy emphasizes code readability with significant indentation.’’’ print(a)  OUTPUT: Python is an interpreted high-level general- purpose programming language. Python's design philosophy emphasizes code readability with significant indentation. 5
  • 6. LOOPING THROUGHA STRING:  For loop:  INPUT: for x in “hello": print(x)  OUTPUT: h e l l o  While loop:  INPUT: st=“hello" i=0 while i<len(st): print(st[i], end=‘ ’)) i=i+1  OUTPUT: hello str = "welcome to Python class " for k in str: if k == 'P': break print(k, end=' ') Output: welcome to str = "welcome to Python class " for k in str: print(k, end=' ') if k == 'P': break Output: welcome to P 6
  • 7. LOOPING CONTD… ## to print names of the list print ("illustration of for loop--- printing names from list") names=["anand", "arun", "akshata", "anusha"] for i in names: print ("hello " , i) print ("COMPLETED ---") # prints all letters except 'a' and 'k' ## illustration of continue ## illustration of logical operators i = 0 str1 = ‘all is well' while i < len(str1): if str1[i] == ‘s' or str1[i] == ‘l': i += 1 continue print('Current Letter :', str1[i]) i += 1 Current Letter : a Current Letter : Current Letter : i Current Letter : Current Letter : w Current Letter : e 7
  • 8. LOOPING CONTD.. """ program to illustrate for loop and multiple if statements with string to count the occurrence of each vowel """ txt='HELLO how are you? I am fine' counta, counte, counti, counto, countu=0,0,0,0,0 for k in txt: if k=='a' or k=='A': counta+=1 if k=='e' or k=='E': counte+=1 if k=='i' or k==‘’I’: counti+=1 if k=='o' or k =='O': counto+=1 if k=='u' or k=='U': countu+=1 print ("Given string is %s " %(txt)) print ("total 'A' or 'a' in the string is: %d " %(counta)) print ("total 'E' or 'e' in the string is: %d " %(counte)) print ("total 'I' or 'i' in the string is: %d " %(counti)) print ("total 'O' or '0' in the string is: %d " %(counto)) print ("total 'U' or 'u' in the string is: %d " %(countu)) Output: Given string is HELLO how are you? I am fine total 'A' or 'a' in the string is: 2 total 'E' or 'e' in the string is: 3 total 'I' or 'i' in the string is: 2 total 'O' or '0' in the string is: 3 total 'U' or 'u' in the string is: 1 8
  • 9. CHECK STRING (PHRASES IN STRINGS):  Normal:  INPUT: txt = ‘happiness is free“ print("free" in txt)  OUTPUT: True  INPUT: txt = “happiness is free” print(“hello” in txt)  OUTPUT: False  With if statement:  INPUT: txt = “happiness is free” if “free” in txt: print("Yes, 'free' is present.")  OUTPUT: Yes, 'free' is present. txt = "The quick brown fox jumps over the lazy dog!" if "fox" in txt: print("Yes, 'fox' is present.") else: print ("No, ‘fox’is not present") ## to check for a phrase in a string >>>txt = "The best things in life are free!" >>>print(“life" in txt) True 9
  • 10. CHECK STRING :  Normal:  INPUT: txt = ‘welcome to python’ print(‘world’ not in txt)  OUTPUT: True  With if statement:  INPUT: txt = “welcome to python“ if “hello" not in txt: print("Yes, ‘hello' is NOT present.")  OUTPUT: Yes, ‘hello' is NOT present. 10
  • 11. STRING LENGTH AND SLICING:  String length:  INPUT: a = "Hello World” print(len(a))  OUTPUT: 11  INPUT: a = “Welcome to Python programming @@@“ print (len(a))  OUTPUT: 33  String slicing:  INPUT: b = "Hello World“ print(b[2:5]) ## from index 2 to index4  OUTPUT: llo  INPUT: b = "Hello World“ print(b[:5]) ## from beginning 5 characters  OUTPUT: Hello 11
  • 12. STRING SLICING METHODS:  From the Start:  INPUT: >>>b = ‘’python is high level programming language“ >>>print(b[:10])  OUTPUT: python is ## consider from the beginning 10 characters and print  Till the End:  INPUT: >>>b = "python is high level programming language“ >>>print(b[10:])  OUTPUT: high level programming language ## skip first 10 characters from the beginning and print remaining till end of string  With Negative indexing  INPUT: >>>b = "python is high level programming language“ >>>print (b[:-5]) OUTPUT: python is high level programming lan >>>print (b[-5:]) OUTPUT: guage 12
  • 13. STRING SLICING CONTD… ## illustration of slicing ## get a range of characters from the complete string >>>txt = "Govt SKSJTI Bengaluru" # print characters in position 5 to 10. (position 11 not included) >>>print(txt[5:11]) SKSJTI ## slicing from the beginning without initial index >>>txt = "Govt SKSJTI Bengaluru" >>>print(txt[:4]) # from start to position 3 Govt ### slicing till the end without last index >>>txt = "Govt SKSJTI Bengaluru" >>>print(txt[7:]) ## from position 7 to last character SJTI Bengaluru ### Negative indexing >>>txt = "Govt SKSJTI Bengaluru" >>> print(txt[-16:-8]) ## position -8 not included SKSJTI B >>>txt = "Govt SKSJTI Bengaluru" >>> print(txt[:-16]) Govt >>>txt = "Govt SKSJTI Bengaluru" >>> print(txt[-9:]) Bengaluru 13
  • 14. BUILT-IN STRING METHODS IN PYTHON:  Upper case:  INPUT: >>> a = "Hello World” >>>print(a.upper())  OUTPUT: HELLO WORLD  Lower case:  INPUT: a = "Hello World“ print(a.lower())  OUTPUT: hello world  capitalize:  INPUT: >>>a = “hello world” >>> print(a.capitalize())  OUTPUT: Hello world  Misc:  INPUT: >>>a = “hello world” >>> print(a.islower())  OUTPUT: True >>>a = “hello world” >>> print(a.isupper())  OUTPUT: False Note:String methods do not modify the original string. 14
  • 15. BUILT-IN STRING METHODS IN PYTHON  Remove Whitespace(strip):  INPUT: >>> a = " Hello World " >>>print(a.strip())  OUTPUT: Hello World ## remove white spaces at the beginning and end of the string >>> a = " our first python prog" >>>print(a.lstrip(‘our’)) OUTPUT: first python prog  Splitting string:  INPUT: >>> a = " hello and welcome” >>>print(a.split())  OUTPUT: ['hello', 'and', 'welcome'] #list with 3 elements >>>a = " hello,how,are,you” >>>print(a.split())  OUTPUT: ['hello,how,are,you'] ## list with single element  INPUT: >>>a = " hello,how,are,you” >>>print(a.split(‘,’))  OUTPUT: ['hello', 'how', 'are', 'you'] ## list with 4 elements ## splits the string at the specified separator and returns a list. Default separator white space >>>a = “but put cut” >>>print(a.split(‘t’))  OUTPUT: ['bu', ' pu', ' cu', ''] 15
  • 16.  Count occurrence:  INPUT: a = "Hello World“ print(a.count(‘l’)  OUTPUT: 3  To find position (index):  INPUT: >>>a = “Hello world” >>> print(a.indix(‘w’)) OUTPUT: 6 BUILT-IN STRING METHODS IN PYTHON  Check for digits:  INPUT: a = "Hello 23“ print(a.isdigit())  OUTPUT: False a = “2345’ print(a.isdigit())  OUTPUT: True  Check for alphabets:  INPUT: a = "Hello 23” print(a.isalpha())  OUTPUT: False >>>a = “hello " >>>print(a.isaplpha())  OUTPUT: False a = “hello" print(a.isaplpha())  OUTPUT: False 16
  • 17.  Concatenation:  INPUT: a = "Hello“ b = "World“ c = a + b d = a + “, " + b print(c) print(d)  OUTPUT: HelloWorld Hello,World BUILT-IN STRING METHODS IN PYTHON Replace a character or string: INPUT: >>>a = “Geeks for Geeks“ print(a.replace(‘G’, ‘W’)) OUTPUT: Weeks for Weeks INPUT: a = “Hello welcome to Python“ print(a.replace(‘Hello’, ‘Krishna’) OUTPUT: Krishna welcome to Python 17
  • 18. LOOPING TO COUNT:  INPUT: word='python program’ count=0 for letter in word: if letter=='p’: count=count+1 print(count)  OUTPUT: 2  INPUT: s = "peanut butter“ count = 0 for char in s: if char == "t": count = count + 1 print(count)  OUTPUT: 3 18
  • 19. PARSINGAND FORMAT STRINGS:  Parsing:  INPUT: st="From mamatha.a@gmail.com" pos=st.find('@’) print('Position of @ is', pos)  OUTPUT: Position of @ is 14  Format:  INPUT: print ('My name is %s and age is %d ’% (‘Arun', 21))  OUTPUT: My name is Arun and age is 21 19
  • 20. STRING FORMATTING  Without built in function:  INPUT: age = 36 print( "My name is John, I am ", + age)  OUTPUT: My name is John,I am 36  With built in function:  INPUT: age = 36 print( "My name is John, I am {} ".format(age))  OUTPUT: My name is John, I am 36 20
  • 21. MULTIPLE PLACE HOLDERS IN STRING FORMAT  Without index numbers:  INPUT: quantity = 3 itemno = 5 price = 49.95 myorder = “I want {} pieces of item {} for {} dollars.“ print(myorder.format(quantity, itemno, price))  OUTPUT: I want 3 pieces of item 5 for 49.95 dollars.  With index numbers:  INPUT: quantity = 3 itemno = 5 price = 49.95 myorder = "I want to pay {2} dollars for {0} pieces of item {1}.“ print(myorder.format(quantity, itemno, price))  OUTPUT: I want to pay 49.95 dollars for 3 pieces of item 5. 21
  • 22. ESCAPE SEQUENCES  To insert characters that are illegal in a string, we use an escape character.  Example:  INPUT: txt = "We are the so-called "Vikings" from the north." print(txt)  OUTPUT: We are the so-called "Vikings" from the north. 22
  • 23. 23
  • 24. STRING COMPARISON:  Normal:  INPUT: >>> print(‘python’==‘python’) >>> print(’Python’< ‘python’) >>> print (’PYTHON’==‘python’)  OUTPUT: True True False .  Using is operator:  >>>str1=‘python’  >>>str2=‘Python’  >>>str3=str1  >>> str1 is str2 False >>> str3 is str1 True >>> str2 is not str1 True >>>str1+=‘s’ >>> id(str1) 1918301558320 >>> id(str2) 1918291321200 >>> id(str3) 1918301558320 >>>id(str1) 1918301822256 The relational operators compare the Unicode values of the characters of the strings from the zeroth index till the end of the string. It then returns a boolean value according to the result of value comparison is and is not operators check whether both the operands refer to the same object or not. If object ids are same, it returns True 24
  • 26. SUMMARY OF BUILT-IN 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 find() Searches the string for a specified value and returns the position of where it was found format() Formats specified values in a string 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 isdecimal() Returns True if all characters in the string are decimals 26
  • 27. CONTD.. isdigit() Returns True if all characters in the string are digits isidentifi er() Returns True if the string is an identifier islower() Returns True if all characters in the string are lower case isnumeri c() Returns True if all characters in the string are numeric isprintab le() Returns True if all characters in the string are printable isspace() Returns True if all characters in the string are whitespaces istitle() Returns True if the string follows the isupper() ReturnsTrue if all characters in the string are uppercase join() Joins the elements of an iterable to the end of the 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 27
  • 28. CONTD.. 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 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 returnsa list rstrip() Returns a right trim version of the string split() Splits the string at the specified separator, and returnsa 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 28