0% found this document useful (0 votes)
39 views25 pages

Unit-2 ch-9 Strings

Uploaded by

kakalachu6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views25 pages

Unit-2 ch-9 Strings

Uploaded by

kakalachu6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Chapter – 9 : Strings in Python

➢ String is one of the most common used data type in Python.


➢ String is a sequence of characters – letters , digits and special symbols
➢ We create a string by enclosing some characters in single (‘) or double (”) or triple quotes.
➢ When we enclose the string in triple quotes, it can span several lines without using the escape
character.

Example of creating a String


➢ >>> a = "hello" # using double quote
➢ >>> b = 'world' # using single quote
➢ >>> s = “””Computer””” # using triple quotes
➢ >>> c = "How're you doing?“ # mixing single and double quotes

1|Page
Empty string:
str=“ “

If string is long then it can be shifted to the next line by typing ‘\’ but it shows
the output in the same line
Str=“ my school is \
the air force school “
This displays output in the same line. (demonstrated on next slide)

We can use escape sequence character also while creating string


str=“We all are indian \n we love our country”
This display output in different lines( from \n onwards)

INPUTING THE VALUE OF A STRING FROM THE USER

2|Page
Traversing a string
➢ Every character in a string is associated with index value 0 to n-1 where ‘n’ is the length of
string
➢ Python indexes the strings in 2 ways :
❑ Positive index (0 to n-1) from left to right
❑ Negative index (-1 to –n) from right to left

STR[0] will display ‘P’ , STR[1] displays ‘Y’ and so on


STR[-1] will display ‘N’ STR[-2] displays ‘O’ and so on

Python Code to iterate each character of the string


Method 1 : By accessing individual character
Str=“Computer Science”
for i in Str:
print(i) or print (i, end=‘ ‘)

Method 2 : By Index Method


str=“Computer Science”
for i in range (0,len(str)): # len() is a function to calculate length of string
print(str[i]) or print (str[i], end=‘ ‘)

String Operators
1. String Operators : + and *
+ means “concatenate” joins the two strings one after the other
* means “replicate “ creates new strings, concatenating multiple copies of the same
string .
Example
Str1=“Hello”
Str2=“World”
print(Str1+Str2) # displays HelloWorld
print( Str1*2) # display HelloHello

3|Page
2. String Membership Operators : in and not in
in : Evaluates to true if it finds a variable in the specified sequence and false
otherwise.
not in : Evaluates to true if it does not finds a variable in the specified sequence and
false otherwise.
Example :
‘H’ in ‘PYTHON’ gives True
‘S’ in ‘PYTHON’ give False
‘H’ not in ‘PYTHON’ gives False
‘S’ not in ‘PYTHON’ gives True

3. Comparision Operator ( any relational operator):


“ arrow” > ”aron” gives True. # it compares character wise considering its ASCII value

4. String slicing ( retrieve substring from a string)


str[start:end] it gives string from start index upto end-1 index.
Example 1 :
Str=“Computer Science”
Str1=str[2:5] gives mpu
While slicing we can use step value also.
Str1=str[2:11:2] gives mue c
Example 2 :
Str=“ computer”
Str[1:3] gives om
Str[:3] gives com
Str[3:] gives puter
Str[:] gives computer
Str[-2:] gives er
Str[:-2] gives comput
Str[::2] gives cmue # step value is 2

4|Page
Immutable nature of strings
Strings in python are immutable which means we cannot make changes in an existing string
As string is immutable, we cannot change any character of string.
Str[3]=‘P’ gives error

5|Page
String Methods
1. len() This gives length of string( number of characters)
Example :
str=“computer”
print(len(str)) gives 8

2. capitalize() This will display string in Sentence case. First character of the string will be in
capital letter
Example :
str=“computer”
print(str.capitalize()) Computer

3. split() Break up a string at the specified separator and returns a list of substring.
str.split(separator, maxsplit)
separator (optional) is a delimiter
maxsplit(optional) is maximum number of splits
Example :
str = ‘this is a python class’
x = str.split()
print(x) #prints [ ‘this’ , ‘is’ , ‘a’ , ‘python’ , ‘class’ ]

6|Page
4. replace() this replace all the occurrence of old substring/string by a new substring/string if
found
Example :
str=“ India is my country”
print(str.replace(“my”, “our”)) now it displays India is our country

5. isalpha() returns True if string contains only letters otherwise returns False
Example :
str=“ India is my country”
str.isalpha() returns True

7|Page
6. isdigit() or isnumeric() returns True if string contains only digits otherwise returns False
Example :
str = ‘abc@123’
str2 = ‘123’
str.isdigit() returns False
str2.isdigit() returns True

7. isspace() Returns True if string contains only space otherwise False


Example :
str=“ “
str.isspace() gives true

8. istitle() Returns True if string is in title case otherwise returns False ( First character of
each word should be in capital)
Example :
str=“The Air Force School”
str.istitle() gives True

8|Page
9. isalnum() It checks whether all characters are only alphabets or digits or not. It returns
accordingly
Example :
str=“abc”
str1 = “@xyz”
str.isalnum() returns True
str1.isalnum() returns False

10. lower() converts string into lowercase letters


Example :
str = “Tafs”
str.lower() prints tafs

11. islower() Returns True if all letters of a string are in lower case otherwise returns False
Example :
str = “Tafs”
str.islower() returns False

9|Page
12. upper() converts string into uppercase letters
Example :
str = “Tafs”
str.upper() returns TAFS

13. isupper() Returns True if all letters of a string are in upper case otherwise returns False
Example :
str = “Tafs”
str.isupper() returns False

14. lstrip() or lstrip(char) Returns the string after removing the leading space or after removing
specific characters from left side
Example :
str=“ computer”
str1=“computer science”
str.lstrip() gives computer
str1.lstrip(‘co’) gives mputer science

15. rstrip() or rstrip(char) Returns the string after removing the leading space or after removing
specific characters from left side
Example :
str=“computer ”
str1=“computer scienceee”
str.rstrip() gives computer
str1.rstrip(‘ee’) gives computer science

10 | P a g e
16. join()
Returns a string in which the string elements have been joined
by a string separator
Example :
str1=‘12345’
s=‘-’
s.join(str) gives 1-2-3-4-5

17. swapcase() converts the cases of character in a string (lower to upper and vice versa)
Example :
str=‘PyTHoN’
str.swapcase() gives pYthOn

11 | P a g e
18. partition(separator) split the string by given string(separator). It gives a tuple.
Example :
str1=‘[email protected]
str2=str1.partition(‘@’)
print(str2) gives ( ‘xyz’, ‘@’, ‘gmail.com’)
str3=str1.partition(‘ ‘)
print(str3) gives (‘[email protected]’, ’ ‘, ’ ‘)

19. count() This method returns number of occurrences of a substring in a string.


Example :
Str1=“ this is my school. It is in subroto park”
Str2=“is”
Str1.count(Str2) gives 3

12 | P a g e
20. ord() this function returns the equivalent ASCII value of a character.
ASCII values are assigned to each character ranges from 0 to 255
A=65, Z=90 a=97 z=122 0(zero)=48 9=57 etc
Example :
ch=‘b’
print( ord(ch)) gives 98

21. chr() this function returns the equivalent character for given ASCII value
Example :
print( chr(97)) gives ‘a’

13 | P a g e
22. find() The method find() determines if string str occurs in string, or in a substring of string if
starting index beg and ending index end are given.
str.find(str, beg,end)
Parameters
str -- This specifies the string to be searched.
beg -- This is the starting index, by default its 0.
end -- This is the ending index, by default its equal to the length of the string.
This method returns index if found and -1 otherwise.
Example :
str1 = "this is string example....wow!!!"
str2 = "exam"
print (str1.find(str2)) returns 15
print (str1.find(str2, 10)) returns 15
print (str1.find(str2, 40)) returns -1

23. rfind() The method is same as find() but searches from end.
str.rfind(str1, beg, end)
Example :
str1 = "this is string example"
str2 = "exam"
print (str1.rfind(str2)) 16

14 | P a g e
24. center() Returns a string with the original string centered to a total of width columns and filled
with fillchar in columns that do not have characters.

25. endswith() Checks if string ends with any substring(given). Returns True if so otherwise False.
You can set beginning index and end index also.
str.endswith(str1, beg, end)
Example :
str=“ The air force school”
str1 = “ol"
print (str.endswith(str1)) gives True

26. startswith() Checks whether string starts with substring.


Example :
str=“python”
print( str.startswith(“py”)) gives True

15 | P a g e
27. index() Same as find but raises error if substring not found.
Example :
str=“ He is my best friend”
print(str.index(“mine’)) raises an error
print(str.index(“be”)) gives 9

28. rindex() Same as index() but it checks from end of string.


Example :
str=“python”
print(str.rindex(“mine’)) raises error

29. ljust() String will be left justified.


Example :
str=“best friend”
print(str.ljust(15,’*’) best friend****

30. rjust() Same as ljust() , String will be right justified.


Example :
str=“python”
print( str.rjust(10, ’*’)) gives ****python

16 | P a g e
31. zfill() returns string left padded with zeros to a total of specified width.
Example :
str=“python”
print(str.zfill(10)) gives 0000python

32. max() Returns the highest alphabetical character( having highest ASCII value).
Example :
str=“best friend”
print(max(str)) gives ‘t’
33. min() Returns the lowest alphabetical character( having lowest ASCII value).
Example :
str=“python”
print( min(str)) gives ‘h’

34. title() returns string in title case


Example :
str=“the air force school”
print(str.title()) gives The Air Force School

17 | P a g e
String Constants:
Many modules in python library provide both functions and constants for dealing with various
elements of the program.
The string module provides various constants that are useful for various purposes.
We need to import string module before using any of the constants of this module with the
following statement:
import string

Constants in string module :


1. string.ascii_uppercase
2. string.ascii_lowercase
3. string.ascii_letters
4. string.digits
5. string.hexdigits
6. string.octdigits
7. string.punctuation
8. string.printable
9. string.whitespace

18 | P a g e
PROGRAMS

19 | P a g e
20 | P a g e
21 | P a g e
22 | P a g e
23 | P a g e
24 | P a g e
25 | P a g e

You might also like