PPS Unit 3 PPT
PPS Unit 3 PPT
-------------------------------------------------
String= Welcome to python
Type= <class 'str'>
Strings :
String Accessing
• We can access each individual character of a string by using index.
• Each character can be accessed in two ways - from the front, or
from the rear end.
• Left to right- Forward index (Positive index)
• Right to left- Backward index (Negative index)
Strings:
mystr="PYTHON"
print("The First character is :",mystr[0])
print("The Third character from :",mystr[-3])
Output :
Output:
String Concatenation :
• The word concatenate means to join together.
• Concatenation is the operation of joining two strings together.
• Python Strings can join using the concatenation operator +.
Example
str="Python"
str1="Programming"
str2="!!"
str3=str+" "+str1+".."+str2
print(str3)
----------------------------------------------
Python Programming..!!
String appending:
• Append means to add something at the end. In python you can add one string at the end of another string
using the += operator.
• "Concatenate" joins two specific items together, whereas "append" adds another string to existing string.
• Ex- 1
s="Py"
s=s+"thon“ or s+="thon“
----------------------------------------------------
Python
• Ex-2
str="hello:"
name=input("Enter name")
str+=name
print(str)
---------------------------------------------------------
Enter name ABC
hello:ABC
Multiplication or Repetition :
• To write the same text multiple times, multiplication or
repetition is used.
• Multiplication can be done using operator *.
Example-
str= "My Class is Best..."
print(str*3)
------------------------------------------
Output :
My Class is Best…
My Class is Best…
My Class is Best…
String Slicing :
• A substring of a string is called slice.
• Slicing is a string operation.
• Slicing is used to extract a part of any string based on a start index
and end index.
• The extracted portions of Python strings called substrings.
• In slicing colon : is used. An integer value will appear on either
side of colon.
• You can take subset of string from the original string by using []
operators also known as slicing operators.
Syntax :
string_name[Start: Stop: Step]
String Slicing :
Example- Output:
str="Python Programming is very interesting" Characters from 3rd to 6 : thon
print("Characters from 1st to 6 :",str[0:6]) Characters from 8th onwards : Programming is very interesting
Characters from 1st onwards : Python Programming is very
print("Characters from 8th onwards :",str[7:]) interesting
print("Characters from 1st onwards :",str[0:]) Last two Characters : ng
print("Last two Characters :",str[-2:]) Characters from Fourth Last onwards : ting
print("Characters from Fourth Last onwards :",str[-4:]) Characters from Fourth Last to Second Last : t
print("Characters from Fourth Last to Second Last :",str[-4:-3]) Reversing Characters of a string : gnitseretni yrev si gnimmargorP
nohtyP
print("Reversing Characters of a string :",str[::-1])
Alternate Characters from 1st to 18th : Pto rgamn
print("Alternate Characters from 1st to 18th :",str[0:17:2])
Strings are immutable
• Immutable- Non-Changeable.
• Whenever you try to modify an existing string variable, a new string is created.
• id() returns the memory address.
• Example-
s="Python"
id(s)
s="Java"
id(s)
----------------------------------------------------------------------
Output-
2375308936240
2375312788528
Note-This means that when you assign a new value to s, a new string object is created rather
than modifying the existing string.
String Formatting
• String formatting is the process of infusing(fill) things in the string
dynamically and presenting the string.
• Formatting with % Operator.
• Formatting with format() string method.
• Formatting with string literals, called f-strings.
• Formatting with String Template Class
String Formatting Operator
• Formatting with % Operator.
• % sign, this string formatting operator is one of the exciting feature in Python.
• The format operator, % allows user to construct strings, replacing parts of strings with the data stored in variables.
• The syntax for the string formatting operator is.
"<Format>" %(<Values>)
Ex-
name= "ABC"
age= 8
print("Name=%s and Age=%d"%(name, age))
print("Name=%s and Age=%d"%('xyz', 10))
-----------------------------------------------------------------------
Name=ABC and Age=8
Name=xyz and Age=10
String Formatting
String Formatting- Example
1. a=‘j’ 6. A=100000
print("a value % c"%a) print("%e"%A)→ 1.000000e+05
2. a=10 7. pi=3
b=20 print("%f"%pi) → 3.000000
print("a value is %d"%a) 8. pi=3.14
print("a value is %i"%a) print("%f"%pi) →3.140000
3. name="abc" 9. 3.140000
print("Name is %s"%name) print("%g"%a) → 3.14
4. a=32768 10. a=10.100000
print("%u"%a) print("%G"%a)→10.1
5. a=10 11. 10.1
print("%o"%a)→12 a=1.000000e+05
print("%x"%a)→a print("%G"%a)→100000
print("%X"%a)→A
String Formatting
• To use two or more argument specifiers, use a tuple (parentheses):
Ex-
name="abc"
age=20
address="xyz, pin 424201“
print("%s\n%d\n%s"%(name, age, address))
----------------------------------------------------------------------
Name=abc
age=20
address=xyz, pin 424201
String Formatters:
• Sometimes, you may want to print variables along with a string.
• You can either use commas, or use string formatters for the
same.
• Ex-
name=input("Enter your name :")
city= "Pune"
country="India"
print("I am",name, "from",city,"\n""I love",country)
-------------------------------------------------------------------------------
Output
Enter your name :ABC
I am ABC from Pune
I love India
String Formatters : Format() method
• The Format() formats the specified values and insert them inside the string
placeholder. The placeholder define using curly bracket {}.
• It has the variables as arguments separated by commas. In the string, use curly
braces to position the variables.
Ex- print("Welcome to {}".format("Python"))
Ex-s1="Hello"
s2="How are you?“
print("Hiii {} {}".format(s1,s2))
print("Hiii {0} {1}".format(s1,s2))
print("Hiii {1} {0}".format(s1,s2))
print("Hiii {}".format(s1,s2))
print("{s2} {s1} How are you?".format(s1="Hii",s2="Hello"))
print("I Like {0}.{1}".format("Python Programming", "Its very interesting"))
print("value of a and b is {a},{b}".format(a=30,b=40))
Formatted String using F-strings
• To create an f-string, prefix the string with the letter “ f ”. The string
itself can be formatted in much the same way that you would with
str.format(). F-strings provide a concise and convenient way to embed
python expressions inside string literals for formatting.
• Ex-
name="abc"
print(f"My name is {name}")
------------------------------------------------------
My name is abc
String Formatters : Template
• This class is used to create a string template for simpler string
substitutions.
Ex-
from string import Template
str=Template('My name is $name and I am from $city studying in $college
College')
str1=str.substitute(name='ABC', city='Pune', college='SKNCOE’)
print(str1)
-----------------------------------------------------------
My name is ABC and I am from Pune and studying in SKNCOE College
built in string methods and functions.
•
ord() and chr() Functions
• The ord() function returns the ASCII code of the character.
• The chr() function returns character represented by a ASCII number.
• ASCII- A to Z(65-90), a to z(97-122), 0 to 9(48-57)
• ord(character)
•
EX-
ch='a'
print(ord(ch))
o/p- 97
Ex-
print(chr(97))
o/p- a
in and not in Operators/ Membership
Operator
• in and not in operator can be used • Ex-
with string to determine whether a a="Welcome to python“
string is present in another string.
• Ex- 'b' in 'apple’
if "to" in a:
→ False print("Found")
• Ex- 'b' not in 'apple’ else:
→ True print("Not Found")
• Ex- Ex- 'a' in ‘a’
→ Found
→True
• Ex- Python' in 'Python’
→ True
Comparing String
• Python allows you to compare strings using relational(or comparison)
operators such as ==, != ,>, < , <=, >= etc.
Iterating string
• String is sequence type(Sequence of character), You can iterate through the string using for loop.
• The for loop executes for every character in str. The loop starts with the first character and
automatically ends when the last character is accessed.
EX-
s="Welcome to Python"
for element in s:
print(element,end="")
Ex-
s="Welcome to python"
for i in range(len(s)):
print(s[i])
Ex-
s="Welcome to python"
for i,ele in enumerate(s):
print(i, ele)
Iterating string
• Iterate string using while loop:
Ex-
s="Welcome to Python"
index=0
while index<len(s):
char=(s[index])
print(char,end='')
index=index+1
The String Module
• The String Module Consist of a number of useful constants, classes, and
functions.
• These function are used to manipulate a string.
• It includes predefined strings that can be helpful for various text processing tasks.
• Example-
import string
Print(dir(string))
-----------------------------------------------------------------------------------------------------
['Formatter', 'Template', '_ChainMap', '__all__', '__builtins__', '__cached__', '__doc__',
'__file__', '__loader__', '__name__', '__package__', '__spec__', '_re', '_sentinel_dict', '_string',
'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'capwords', 'digits', 'hexdigits', 'octdigits',
'printable', 'punctuation', 'whitespace’]
The String Module
• To Know details of particular items.
type(string.digits)
<class 'str’>
• import string
• string.digits
'0123456789’
• import string
string.__builtins__.__doc__
The String Module
Example- Output
import string Digits= 0123456789
print("Digits=",string.digits) Punctuation= !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
print("Punctuation=",string.punctuation) Letters=
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQR
print("Letters=",string.ascii_letters) STUVWXYZ
print("Uppercase=",string.ascii_uppercase) Uppercase= ABCDEFGHIJKLMNOPQRSTUVWXYZ
print("Lowercase=",string.ascii_lowercase) Lowercase= abcdefghijklmnopqrstuvwxyz
print("Printable=",string.printable) Printable=
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHI
JKLMNOPQRSTUVWXYZ!"#$%&'()*+,-
./:;<=>?@[\]^_`{|}~
Practical on Unit III
1. Program to concatenate two string using + operator.
2. Program to append a string using += operator.
3. Program to display power of a number without using formatting characters.
4. Program to display power of a number using formatting characters.
5. Program to demonstrate slice operation on string objects.
6. Program to understand how characters in a string are accessed using negative indexes.
7. Program to understand ord() and char() function.
8. Program that uses split() to split a multiline string.
9. Program that counts the occurrences of a character in a string. Do not use built in function.
10. Program to reverse of string by user defined function.
11. Write a python program that accepts a string from user and perform following string
operations- i. Calculate length of string ii. String reversal iii. Equality check of two strings iii.
Check palindrome ii. Check substring