Unit IV
Strings
Subject :PPS
Subject Teacher :Ms.Mhaske N.R.
Ms.Mhaske N.R. (PPS) 2
Introduction
● String is a data type in python
● String is a sequence made up of one or more individual characters
● Where characters could be a letter, digit,whitespace or any other
symbol
● Python has inbuild class name 'str' that has many useful feature
● We can declare and define a string by creating a variable of string type.
● String literal can be enclosed by either triple, double,or single quotes.
● Escape sequence with each type of string literal
● E,g. name=”India”
● Graduate='B.E.'
Ms.Mhaske N.R. (PPS) 3
Reading and Converting
• We prefer to read data
in using strings and
then parse and convert
the data as we need
• This gives us more
control over error
situations and/or bad
user input
• Raw input numbers
must be converted
from strings
>>> name = raw_input('Enter:')
Enter:Chuck
>>> print name
Chuck
>>> apple = raw_input('Enter:')
Enter:100
>>> x = apple – 10
Traceback (most recent call last):
File "<stdin>", line 1, in
<module>TypeError: unsupported
operand type(s) for -: 'str' and 'int'
>>> x = int(apple) – 10
>>> print x
90
Indexing
• We can get at any single
character in a string using
an index specified in square
brackets
• The index value must be an
integer and starts at zero
• The index value can be an
expression that is computed
>>> fruit = 'banana'
>>> letter = fruit[1]
>>> print letter
a
>>> n = 3
>>> w = fruit[n - 1]
>>> print w
n
00
bb
11
aa
22
nn
33
aa
44
nn
55
aa
Traversing a string
● A string can be traversed by accessing characters from one index to another
● E,g.
message=”hello”
Index=0
for i in message:
print(“message[“ , index,” ] ”= ”, i)
index += 1
OUTPUT: message[0]=h
message[1]=e
message[2]=l
message[3]=l
message[4]=o
●
Concatinating,Appending and Multiplaying
strings
● Concatenate :means to join together
● '+' opeartor is used for concating purpose.
● The * operator can be used to repeat the string for a given number of
times.
str1 = 'Hello'
str2 ='World!'
# using +
print('str1 + str2 = ', str1 + str2)
# using *
print('str1 * 3 =', str1 * 3)
OUTPUT:
tr1 + str2 = HelloWorld!
str1 * 3 = HelloHelloHello
● Append a string :to add something at the end.
● In python you can add one string at the end of another string using the
' +=' operator
● E.g.
Str='hello'
name=raw_input(“n enter your name”)
str+=name
Str+=”.welcome to pune”
print(str)
Output:
enter your name:ashish
hello ashish.welcome to pune
● Iterating Through String :Using for loop we can
iterate through a string. Here is an example to count
the number of 'l' in a string.
count = 0
for letter in 'Hello World':
if(letter == 'l'):
count += 1
print(count,'letters found')
OUTPUT:
3 letters found
String Membership Test
● We can test if a sub string exists within a string or not, using the
keyword in
>>> 'a' in 'program'
True
>>> 'at' not in 'battle'
False
String are Immutable
● Python string are immutable
● That is once created they cannot be changed.
● Whenever you try to modify an existing string variable, a new string is
created.
● Every object in python is stored in memory .
● You can find out whether two varibles are referring to the same object or not
by using the id().
● The id() returns the memory address of that object.
● As both str1 and str2 points to same memory location, they both point to the
same object
str1=”Hello”
print (“str1 is “,str1)
print(“id of str1 is”, id(str1))
str2=”world”
print(“str2 is”,str2)
print(“id of str2 is”,id(str2))
str1+=str2
print(“str1 after modification”,str1)
print(“id of str1 is”, id(str1))
str3=str1
print(“str3 is”,str3)
Print( “id of str3 is”, id(str3)
Output:
Str1 is Hello
id of str1 is 45093344
Str2 is world
id of str1 is 45093312
str1 after modification: Helloworld
Id of str1 is 43861792
Str3 Helloworld
Id of str3 is 43861792
Escape characters and their meaning
Escape character Meaning
a Bell or alert
b backspace
n New line
t Horizontal tab space
v Vertical tab space
r Enter button
x Character x
 Display single
● Raw String to ignore escape sequence
● Sometimes we may wish to ignore the escape sequences inside a string. To
do this we can place r or R in front of the string. This will imply that it is a raw
string and any escape sequence inside it will be ignored.
>>> print("This is x61 ngood example")
This is a
good example
>>> print(r"This is x61 ngood example")
This is x61 ngood example
Python String Formatting
● Escape Sequence
●
If we want to print a text like -He said, "What's there?"- we can neither use single quote or double
quotes.
●
An escape sequence starts with a backslash and is interpreted differently. If we use single quote to
represent a string, all the single quotes inside the string must be escaped. Similar is the case with
double quotes.
# using triple quotes
print('''He said, "What's there?"''')
# escaping single quotes
print('He said, "What's there?"')
# escaping double quotes
print("He said, "What's there?"")
OUTPUT :He said, "What's there?"
He said, "What's there?"
He said, "What's there?"
Formating symbol
Format symbol Purpose
%c character
%d or %i Signed decimal integer
%s string
%u Unsigned decimal integer
%o Octal integer
%x or %X Hexadecimal integer
%e or %E Exponential notation
%f Floating point number
%g or %G Short number in floating point or
exponential notation.
● The syntax for string formatting opeartion is:
“<format>” % (<Values>)
● The statement began with a format string consisting of a sequence of characters and
conversion specifications.
● Conversion specification start with a % opeartor and can appear anywhere within the
string.
● Following the format string is a % sign and the a set value ,one per conversion
specification , seperated by commas and enclosed in parathesis. If ther is single value
then parenthesis is optional.
● E,g,
name=”ashish”
Age=8
print(“name=%s and age=%d” %(name,age))
print(“name=%s and age=%d”m, %(“ankita”,6))
Output:
name=ashish and age=8
name=ankita and age=6
● Formatting a string means presenting the string in a clearly understandable
manner.
● The format method is used to format the string
● This methos is used as
'formatstring with replacement field'.format(value)
● E.g. id=10, name='shankar' sal=20000
1) Str='{},{},{}'.format(id,name,sal)
print(str) #output=10,shankar,20000
2) Str='{} - {} - {}'.format(id,name,sal)
print(str) #output=10 – shankar – 20000
3 )Str='id={}n name={}n sal={}'.format(id,name,sal)
print(str) #output=
id=10
name=shankar
sal=20000
Built-in string methods and functions
● String are an example of python objects.
● An object is an entity that contains both data(the actual string
itself) as well as functions to manupulate that data.
● These functions are availble to any instance(variable) of the object
● Python supports many built-in methods.
● A methods is just like a function.
● The only difference between function and tring methods is invoked
or called on an object.
● e.g. if the varible str is a string, then you can call the upper()
methods as str.upper() to convert all the characters of str in
uppercase.
Python has a set of built-in methods that you can use on
strings.
/media/admin1/HP x740w/PPS PPT/UNIT iv/in built function in string.pdf
String methods
Function Usage Example
Capitalize() To capitalize first letter of the string str=“hello”
print(str.capitalize())
O: Hello
Center(width,fillchar) Returns string with the original string
centered to a total of width columns and filled
with fillchar in columns that do not have
characters
Str=“hello”
print(str.center(10,’*’))
O: **hello***
Count(str,beg,end) Counts number of times str occurs in a
string.
msg=“my best friend”
print(msg.endswith(“end”,0,
len(msg)))
O: True
Endswith(suffix,beg,end) Checks if string ends with prefix msg=“my best friend”
print(msg.endswith(“end”,0,
len(msg)))
O: True
startswith(suffix,beg,end) Checks if string starts with prefix msg=“my best friend”
print(msg.startswith(“my”,0,
len(msg)))
O: True
Find(str,beg,end) Checks if str is present in string. msg=“my best friend”
print(msg.find(“best”,0, len(msg)))
O: 3
Index(str, beg, end) Same as find but raises an exception if str
is not found
msg=“my best friend”
print(msg.index(“mine”,0,
len(msg)))
O: valuerror:substring not found
String methods
Function Usage Example
Rfind(str,beg,end) Same as find but starts searching from
the end
msg=“my best friend”
print(msg.rfind(“best”,0, len(msg))
O: 3
Rindex(str,beg,end) Same as index but starts searching from
the end and but raises an exception if
str is not found
msg=“my best friend”
print(msg.rindex(“my”,0, len(msg))
O: 0
Isalnum() Returns True if string has at least one
character and every character is either
a number or an alphabet
msg=“jamesbond007”
print(msg.isalnum())
O: True
Isalpha() Returns True if string has at least one
character and every character is an
alphabet
msg=“jamesbond007”
print(msg.isalpha())
O: False
Isdigit() Returns True if string contains only
digits
msg=“007”
print(msg.isdigit())
O: True
Islower() Returns True if string has at least one
character and every character is a
lowercase alphabet
msg=“Hello”
print(msg.islower())
O: False
Isspace() Returns True if string contains only
whitespace characters
msg=“ “
print(msg.isspace())
O: True
Isupper() Returns True if string has at least one
character and every character is a
uppercase alphabet
msg=“HELLO”
print(msg.isupper())
O: True
String methods
Format Usage Example
len(string) Returns the length of the string str=“hello”
print(len(str))
O : 5
ljust(width,[fillchar]) Returns a string left justified to a total of width columns. Columns
without characters are padded with the character specified in the
fillchar argument
str=“hello”
print(ljust(10,”’*’))
O : hello*****
rjust(width,[fillchar]) Returns a string right justified to a total of width columns.
Columns without characters are padded with the character
specified in the fillchar argument
str=“hello”
print(rjust(10,”’*’))
O : *****hello
zfill(width) Returns string left padded with zeros to a total of width
characters.
str=“1234”
Print(str.zfill(10))
O:0000001234
lower() Converts all characters in the string into lowercase str=“Hello”
print(str.lower())
O : hello
upper() Converts all characters in the string into uppercase str=“hello”
print(str.upper())
O : HELLO
lstrip() Removes all leading whitespace in string str=“hello”
print(lstr.lstrip())
O : hello
String methods
Format Usage Example
rstrip() Removes all trailing whitespace in string str=“hello ”
print(rstr.lstrip())
O : hello
strip() Removes all leading and trailing whitespace in string str=“ hello ”
print(str.lstrip())
O : hello
max(str) Returns the highest alphabetical character (having highest
ASCII value) from the string str
str=“hello friendz”
print(max(str))
O : z
min(str) Returns the lowest alphabetical character (having lowest ASCII
value) from the string str
str=“hello friendz”
print(min(str))
O : d
replace(old,new[,
max])
Replaces all or max occurrences of old in string with new str=“hello hello hello”
Print(str.replace(“he”,”fo”))
O:follo follo follo
title() Return string in title case str=“python language”
Print(str.title())
O: Python Language
swapcase() Toggles the case of every character str=“python Language”
Print(str.swapcase())
O: PYTHON lANGUAGE
String methods
FormatFormat UsageUsage ExampleExample
split(delim) Returns a list of substrings seperated by the
specified delimiter. If no delimiter is specified
then by default it spilts strings on all whiespace
characters
str=“abc,def,ghi,jkl”
print(str.split(,))
O: [‘abc’,’’def’,’ghi’,’jkl’]
join(list) Joins a list of strings using the delimiter with
which the function invoked.
print(‘-’.join([‘abc’,’def’,’gh
i’,’jkl’])
O:abc-def-ghi-jkl
isidentifier() Returns true if the string is a valid identifier str=“hello”
print(str.isidentifier())
O: True
enumerate(str) Returns an enumerate object that lists the
index and value of all the characters in the
string as pairs
str=“hello”
print(list(enumerate(str))
O: [(0,’h’),(1,’e’),(2,’l’),
(3,’l’),(4,’o’)]
Ord() and chr() functions
● Ord() : function returns the ASCII code of the
character
● Chr() :function returns character represented by
ASCII number.
● e.g.
ch=='R'
ptint(ord(ch))
Output: 82
Print (chr(82))
Output: R
Comparing string
● Python allows you to compare strings using relational (or comparison)
operator such as >,<.<=,>=, etc.
● ASCII value for A-Z is 65-90 and a-z is 97-122
Operator Description example
== If two strings are equal , it return
true
>>>”AbC”==”AbC”
True
!= or <> If two strings are not equal , it returns
true
>>”abC”!=”Abc”
True
> If the first string is greater than
second,it returns true
>>>”abc”>”Abc”
True
< If the second string is greater than
first,it returns true
>>>”abC”<”abc”
True
>= If the first string is greater than or equal
to the second,it return true
>>>”aBC”>=”ABC”
True
<= If the second string is greater than or
equal to the first,it return true
>>>”Abc”<=”ABc”
True
Exmaples
>>>“TED” ==”ted”
False
>>>”tend”<=”tent”
True
>>>”main”<=”main”
● True
SLICE Operation
● A substring of a stirng is called a slice.
● The slice operation is used to refer to sub parts of sequence and
string
● You can take subset of a string from the original string by using [ ]
operator also known as slicing operator.
● e.g. string with indexing
●
The syntax of slice opeartion is s[start:end]
● Where start specifies the beginning index of the substring and end-1 is the index of
the last chacters.
● Eg
str=”python”
print(“str[1:5]=”,str[1:5])
print(“str[:6]=”,str[:6])
print(“str[:]=”,str[:])
print(“str[1:20]=”,str[1:20])
● Output:
str[1:5]=ytho
Str[:6]=python
Str[:]=python
Str[1:20]=ython
● Slice opration with negative index
str=”python”
print(“str[-1]=”,str[-1])
print(“str[-6]=”,str[-6])
print(“str[-2:]=”,str[-2:])
print(“str[:-2]=”,str[:-2])
print(“str[-5:-2]=”,str[-5:-2])
● Output:
str[-1]=N
str[-6]=p
str[-2:]=on
str[:-2]=Pyth
str[-5:-2]=yth
●
Specifying stride while slicing strings
● In the slice operation , you can specify a third argument as the stride.
● Which refers to the number of characters to move forward after the first character is retrieved from the string.
● The default value of stride is 1.
str=”welcome to the world of python”
print(“str[2:10]=”,str[2:10])
print(“str[2:10:1]=”,str[2:10:1])
print(“str[2:10:2]=”,str[2:10:2])
print(“str[2:13:4]=”,str[2:13:4])
Output:
str[2:10]=lcome to
Str[2:10:1]=lcome to
Str[2:10:2]=loet
str[2:13:4]=le
● Program to demonstrate slice opration with just
last(neagtive)argument.
● i.e print string in reverse order
str=”welcome to learn python:
print(“str[:-1]=”,str[::-1])
Output:
Str[:::-1]=nohtyp nrael ot emoclew
● Print[::-3]=nyr c
The string module
● The string module consists of a number of useful constant, classes and function.
● These functions are used to manipulate strings
●
String constant:some constant define in string modules are:
– string.ascii_letters:combination of ascii_lowercase and ascii_uppercase constant
– string.ascii_lowercase:refers to all lowercase letters from a-z
– string.ascii_uppercase:refers to all uppercase letters A-Z
– string.digit:refers to digit from 0-9
– string.hexdigit:refers to hexadecimal digit from 0-9,a-f and A-F
– string.lowercase:a string that has all the characters that are considered lowercase letters.
– string.octdigits:refers to octal,0-7
– string.punctuation:string of ASCII characters that are considered uppercase letter
– string.printable: string of printable characters which include digit,letter,punctucation, and whitespce.
– string.upperrcase:a string that has all the characters that are considered uppercase letters
– string.lowercase:a string that has all the characters that are considered lowercase letters
– string.whitespace:a string that all characters that are considerd whitespace like space, tab etc.
Str=”welcome to the world of python”
print(“uppercase=”,str.upper())
print(“lowercase=”,str.lower())
print(split=”,str.split())
print(“join =”,'-'.join(str.split()))
print(“replace=”,str.replace(“python”,”java”))
print(“count of o”,str.count('o'))
print(“find of=”,str.find(“of”))
Output:
Uppercase=WELCOME TO THE WORLD OFPYTHON
lowercse=welcome to the world of python
Split =['wlcome','to', 'the',' world', 'of', 'python']
join=welcome- to- the- world -of -python
Replace-welcome to the world of java
Count of o -5
Find of-21
String module
To see the content of string module, use dir() with the modulename.
>>>dir(string)
To know the details of perticuler item, you can use the type command.
e.g.
Import string
Print(type(string.digits))
OUTPUT:
<class ‘str’>.
import string
print(string.digits)
OUTPUT:
0123456789
Working with constants in string module
import string
print(‘g’ in string.lowercase)
OUTPUT:
True
Programming Examples
1.Write a program to print the follewing pattern
A
AB
ABC
ABCD
ABCDE
ABCDEF
2. Write a program that takes users name and PAN card number as
input.Validate the information using isX function and print the details.
.3. Write a program that encrypts a message by adding a key value to every
character
If key=3, then add 3 to every character
4. Write a program to reverse a string.