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

String

The document provides a comprehensive overview of string manipulation in Python, covering topics such as string immutability, indexing, slicing, and various string methods. It explains how to create, modify, and analyze strings using built-in functions and operators, including concatenation, replication, and membership checks. Additionally, it includes examples of common string methods like capitalize, find, islower, and replace, along with their outputs.

Uploaded by

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

String

The document provides a comprehensive overview of string manipulation in Python, covering topics such as string immutability, indexing, slicing, and various string methods. It explains how to create, modify, and analyze strings using built-in functions and operators, including concatenation, replication, and membership checks. Additionally, it includes examples of common string methods like capitalize, find, islower, and replace, along with their outputs.

Uploaded by

pyushr013
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 70

String is the combination of alphanumeric

characters.

st=“I am good 123”


print(st)
String is an immutable data type
So a particular character in a string cannot
be changed.
st=“this is fine”
st[2]=‘p’
This kind of item assignment is not possible.
So if any one attemps to do it, the program
will throw an error.
Single line strings are enclosed in single
quote or double quote

st=“ I am fine”
st=‘we are good’
print(st)
Multiline strings can be written 2 ways.
Multiline string can be enclosed in a single
quote with back slash at the end of every
line as shown below:
st=“i\
am\
good.”
Multiline string can be enclosed in triple
quote as shown in the following statement

st=“ “”I
Am
Good.”””

Strings which are terminated with EOL take


one byte extra.
st=" i\
am\
good"
l=len(st)
print("length of",st,"is",l)
st="""i
am
good"""
l=len(st)
print("length of",st,"is",l)
OUTPUT:-

length of iamgood is 7

length of i
am
good is 9
Strings can be fetched both in the forward
direction and backward direction

-9 -8 -7 -6 -5 -4 -3 -2 -1

E X C E L L E N T

0 1 2 3 4 5 6 7 8
Single element of string can be printed in
the following manner by using either
forward index or backward index.
-9 -8 -7 -6 -5 -4 -3 -2 -1
E X C E L L E N T
0 1 2 3 4 5 6 7 8

Print(st[3]) will print E


Print (st[-2]) will print N
When you are fetching the string in forward
direction the index starts from 0.

When you are fetching the string in


backward direction the index starts from -1
and ends at –l.(ie - length of the string)
concatenation operator can be used to
concatenate two strings.
st1=“very “
st2=“good”
print(st1+st2)
Output-very good
Concatenation operator takes both as
strings.
Replication operator replicates the string as
per the number specified.
st=“good”
print(st*3)
Output:-
goodgoodgood
The replication operator takes one string
and one number to replicate the original
sring.
Membership operator can be used to check
the presence one charcter in the string

st=“excellent”

Print(“e” in st)—True
Print(“x” in st)-False
Relational operators can be used with
strings
s1=“good”
s2=“Good”
print(s1==s2)
print(s1<s2)
print(s1>s2)
print(s1<=s2)
print(s1>=s2)
Print(s1!=s2)
Output:-

False
False
True
False
True
True
ord(‘a’) function is used to convert the
character to respective ASCII value
C=ord(‘a’)
Print©--output 97
chr(97)-is used to convert the given ASCII to
the respective character
C=chr(97)
print©-’a’
String slices:-

Part of the string can be extracted by using


string slices.

Slicing range is given in the form of


[start:end:updation]
Start is from which index it has to start

End is till where you have to extract. The


string will be fetched one less than end
value

Updating is as per the number specified.


In the similar way, we can fetch the reverse also
then first parameter is greater than second
parameter .

End index is provided followed by start index.


Then the loop will run reverse and extract the
string accordingly.

Here in this scenario, the updating statement will


be decremented as you are fetching from end to
beginning.
st="amazing work"
l=len(st)
print(st)
print("length of the string is",l)
print(st[0:5:1])
print(st[1:10: ])
print(st[3:(l-1):2])
OUTPUT:-
amazing work
length of the string is 12
amazi
mazing wo
zn o
print(st[0: l: ])
print(st[0: :])
print(st[ : : ])
print(st[ : :1])
print(st[0:15:1])
print(st[0:8:3])
OUTPUT
amazing work
amazing work
amazing work
amazing work
amazing work
azg
print(st[-1:-9:-1])
print(st[-1:-15:-2])
print(st[-1:-15:-1])
print(st[9:2:-1])
print(st[::-1])
print(st[11: :-1])
print(st[11: :-1])
OUTPUT
krow gni
ko nzm
krow gnizama
ow gniz
krow gnizama
krow gnizama
krow gnizama
str="amazing work"
print(str[9:3:])# will not work reverse will
not run without third step
print(str[9:3:-1])
print(str[-1:-4:])
print(str[-4:-1])
print(str[4:1])#won't work
print(str[-9:-1])
print(str[:5:])
OUTPUT:-
ow gni

wor

zing wor
amazi
print(str[ :-5])
print(str[-12:-5:1])
print(str[9:-5:1])#no output
print(str[0:-5:1])#important
print(str[0:-5:-1])#no output
print(str[:-4:-1])
print(str[:-4:])
OUTPUT:

amazing
amazing

amazing

kro
amazing
str="excellent"
print(str[4:+4])
print(str[:4]+str[:5])
print("printg entire string")
print(str[:4]+str[4:])
print(str[2:8:2])
print(str[1:])
OUTPUT:
exceexcel
printg entire string
excellent
cle
xcellent
print("printing reverse of the string")
print(str[::-1])
print(str[-1: :-1])
print(str[::1])
print(str[-1:-1 :-1])#no output
OUTPUT:

printing reverse of the string


tnellecxe
tnellecxe
excellent
st="excellent"
print(st[ :3]+st[3:])
print(st[5:-7:-1])
print(st[-5:-1:1])
print(st[ :-4]+st[-4:-1:1])
print(st[0::-1])
print(st[0:-10:-1])
Output:
excellent
lle
llen
excellen
e
e
st="excellent"
l=len(st)
print( st[:-9:-1])
print(st[ :-1:1])
print(st[-8:6:1])
print(st[::-1])
print(st[8::-1])
print(st[-1::-1])
print(st[-1:-10:-1])
print(st[8:0:-1])
Output:
tnellecx
excellen
xcell
tnellecxe
tnellecxe
tnellecxe
tnellecxe
tnellecx
print("Start and end same")
print(st[8:-1:-1])#START AND END SAME
print(st[-5:3:-1])
print(st[-4:7:1])
print(st[-4:7:-1])
print("both start and end are same")
print(st[8:8:])
Output:

Start and end same

l
le

both start and end are same


String slice can be assigned to another
string as shown below:
S=“excellent”
ns=s[2:5:]
print(ns)
Output
cel
1. Capitalize()-makes the first letter of
accepted string capital.
str=input("enter the string")
print(str.capitalize())

OUTPUT:-
enter the string i love my country
I love my country
2.Find() function finds the index of sub
string from initial index to final index.
str=input("enter the string")
sub="love"
print(str.find(sub, 2,9))
Output:-
enter the string
i love my lovely country
2
3. Islower() checks whether string is in lower
or not. If lower returns True else returns
False
str=input("enter the string")
# If accepted string is in lower case
print("is lower")
print(str.islower())
OUTPUT:-
is lower
True
4. isupper() checks whether string is in upper
case or not. If upper returns True else returns
False
str=“bright”
print(str.isupper())

Output_
False
5. isspace()- checks whether the character is
space or not. If str contains only space then it
returns True otherwise it returns False
st=“bright”
print(str.isspace())
Output:
False
st=" “
print(st.isspace())
OUTPUT:-
True
6. isalpha() checks whether it contains
alphabet or not . If string contains only
alphabets then return True othewise returns
False
str=input("enter the string")
print(str.isalpha())
Output:-
enter the string this is good123
False
7. isdigit() checks whether it contains only
digits or not . If string contains only digits
then return True othewise returns False
str=input("enter the string")
print(str.isdigit())

enter the string this is good123


False
8. isalnum() checks whether it contains only
alphabets and numbers . If string contains
only alphabets and numbers then return
True othewise returns False
str=input("enter the string")
print(str.isalnum())
Output:-
enter the string this is good123
False
str="This123"
print(str.isalnum())

OUTPUT:

True
9. lower()- converts the string to lower case
str=“Go Slow”

Output:
go slow
10. upper()- converts the string to upper
case.

print(str.upper())

GO SLOW
11.strip()- strip off the space on both sides
of the string if string contains space

st=“ excellent ”

print(st.strip())
OUTPUT-excellent
12.lstrip(para)- strip off the characters
passed as parameter from strings if they
occur in contiguous cells of the string from
left hand side of the string.
st=“excellent”
print(st.lstrip("ell"))
OUTPUT:
xcellent
13. rstrip(para)- strip off the characters
passed as parameter from string if they
occur in contiguous cells of the string from
the right hand side of the string.

st=“excellent”
print(st.rstrip(“ent"))

OUTPUT
excell
st="saregamapadhanisa"
print(st.rstrip("races"))
print(st.rstrip("tears"))
print(st.rstrip("asian"))
print(st.lstrip("sargam"))
Output:-
saregamapadhani
saregamapadhani
saregamapadh
egamapadhanisa
14. join() function joins the character after
every character of the string which is
passed as a parameter
st2=“*”
st=“excellent”
st1=st2.join(st)
print(st1)
OUTPUT:
e*x*c*e*l*l*e*n*t
Join() function taking list of strings as a
parameter
It will join both strings of the list by inserting
character which is used for joining as shown
in the following example.
st2=“*”
st=“excellent”
st1=st2.join([“very”,st])
print(st1)
OUTPUT:
very * excellent
15. split()-function splits the string at the
character which is passed as a parameter
resulting to list of strings excluding the passed
character.
st2=“*”
st=“excellent”
st1=st2.join([“very”,st])
print(st1)
s=st1.split(st2)
print(s)
OUTPUT:
very * excellent
s=“this is very good”
st1=s.split(“ ")
print(st1)

OUTPUT:

[“this”, “is”, “very”,”good”]


16. replace() replaces the occurrence of first
parameter in the string with the second
parameter which are passed as a parameter.
The change won’t happen in original string
st="beauty"
print(st)
print(st.replace("y","iful"))
print(st)
print("after assigning to a new variable")
t=st.replace("y","iful")
print(t)
print(st)
OUTPUT
beauty
beautiful
beauty
after assigning to a new variable
beautiful
beauty
17. endswith() checks whether the string
ends with character passed as a parameter
and returns true if ends with character
passed as a parameter else returns false.
st=input("accept")
if st.endswith("y"):
print(st[0:len(st)]+" beautiful")
print(st)
nstr=(st[0:len(st)]+" beautiful")
str=nstr
print(str)
OUTPUT

Accept
beauty
beauty beautiful
beauty
beauty beautiful
18. startswith() checks whether strings
starts with character passed as a
parameter, if so returns true otherwise
returns false.
st=input("enter the string")
print(st)
if st.startswith("e"):
print(st)
else:
print("does not start with e")
Output

enter the string excellent


excellent
19. title() function makes the every first
character of the word capital.
st="excellent work"
st=st.title()
print(st)
output
Excellent Work
20. Count() function counts how many times
the passed character appears in the string
. It returns the number of occurrence and
can be assigned to a variable.
st=“excellent”
c=st.count("e")
print(c)
Output
3
21. parition() makes the partition at the
character which is passed as a parameter
to the string and retrieves the contents
as a tuple keeping the parameter as an
individual string within the tuple
st="excellent work“
st=st.partition("w")
print(st)
Output:-
('excellent ', 'w', 'ork')
22. index() function retrieves the index of the
character of the string which is passed as a
parameter. If the passed parameter is not
existing then it will throw “Value error”.

st=“excellent”
print(st.index(“l”))

Output
4
23. Len() is used to find out the length of
the string and returns the length.
st=“ Excellent”
l=len(st)
print(l)
Output:

You might also like