0% found this document useful (0 votes)
10 views28 pages

Strings: New Syllabus 2022-23

secret toppers

Uploaded by

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

Strings: New Syllabus 2022-23

secret toppers

Uploaded by

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

New

syllabus
2022-23

Chapter
11
Strings
String

String is a sequence of characters,which is


enclosed between either single (' ') or double
quotes (" "), python treats both single and
double quotes same.

Visit : python.mykvs.in for regular


String

Creating String
Creation of string in python is very
easy.
e.g.
a=‘Computer Science'
b=“Informatics Practices“
Accessing String
Elements e.g. OUTPU
str='Computer Sciene' T
print('str-', str) Computer Sciene
print('str[0]-', str[0]) C
print('str[1:4]-', str[1:4]) omp
print('str[2:]-', str[2:]) mputer Sciene
print('str *2-', str Computer ScieneComputer Sciene'
*2 )
print("str +'yes'-", str Computer Scieneyes
+'yes')
Visit : python.mykvs.in for regular
String

Iterating/Traversing through string


Each character of the string can be accessed sequentially
C
for loop.
using o
m
p
e.g.
u
t
e
str='Computer Sciene‘ OUTPUT r
S
for i in
c
str: i
print(i)
e

n
Visit : python.mykvs.in for regular
String

Iterating/Traversing through string


Each character of the string can be accessed sequentially
C
for loop.
using

e.g.

name = ‘superb’
OUTPUT
for ch in name:
print(ch,’-’,end=“ “ )

Visit : python.mykvs.in for regular


Program to read a string and display it in reverse
order. Display one character per line
String
str = input("Enter string")
length = len(str)
for i in range(length-1,-1,-1):
print(str[i])
C
Program to read a string and display it in form
First character last character
Second character second last character
str = input("Enter string")
length = len(str)
i=0
for r in range(length-1,-1,-1):
print(str[i], “ “, str[r])
i += 1

Visit : python.mykvs.in for regular


String

String operations
Concatenation + adding 2 strings
5+3=
‘5’ + ‘3’ =
‘5’ + 3

String Replication

3 * “come” =
“1” * 2 =
2*3=
“2” * 3 =
“2” * “3” =
String
sub = “ help”
string = “helping hand”
sub2 = “HELP”
sub in string
sub2 in string
sub not in string
sub2 not in string
String
String comparison
We can use ( > , < , <= , <= , == , != ) to compare two strings.
Python compares string lexicographically i.e using ASCII value
of the characters.
Suppose you have str1 as "Maria" and str2 as "Manoj" . The
first two characters from str1 and str2 ( M and M ) are
compared. As they are equal, the second two characters are
compared. Because they are also equal, the third two
characters ( r and n ) are compared. And because 'r' has
greater ASCII value than ‘n' , str1 is greater than str2
e. .g.program OUTPUT
Fals
print("Maria" == "Manoj") e
print("Maria" != "Manoj") True
print("Maria" > "Manoj")
print("Maria" >= "Manoj") True
print("Maria" < "Manoj")
print("Maria" <= "Manoj") True
print("Maria" > "")
Fals
Visit : python.mykvs.in for regular
String
Determining ordinal or Unicode value of a character
Syntax
ord(single-character)

Syntax
chr(ordinal-value)

chr(65)

ord(‘A’)

Visit : python.mykvs.in for regular


String
Updating Strings
String value can be updated by reassigning another value
in it. e.g.
var1 =
'Comp Sc'
var1 = var1[:7] + ' with Python'
print ("Updated String :- ",var1 )

OUTPUT
Comp Sc with Python

Visit : python.mykvs.in for regular


String Slicing
Refers to the part of the string sliced using range of indices

word = “amazing”

word[0:7]

word[0:3]

word[2:5]

word[-7:-3]

word[-5:-1]
Note : Character at last index(given after :) is not included
String Slicing
Refers to the part of the string sliced using range of indices

word = “amazing”

word[:7]

word[:5]

Word[3:]

Word[5:]
String Slicing
Refers to the part of the string sliced using range of indices
0 1 2 3 4 5 6
a m
word = “amazing” a z i n g
-7 -6 -5 -4 -3 -2 -1

Specify third index – step count


Word[-3::] ‘ing’
word[1:6:2] ‘mzn’
Word[-3::-1]
‘izama’
Word[::-2] ‘giaa’
Word[4:8]
‘ing’
Word[-7:-3:2] ‘aa’ Word[7:10]
Word[::-1] ‘‘
‘gnizama’ Word[-1::-1]
Program to print the given string as palindrome or not
using string slicing
s=input(“Enter String”)
if(s == s[::-1]):
print(“Palindrome”)
else:
print(“Not “)
String

Triple Quotes
It is used to create string with multiple lines.

e.g.
Str1 = “””This course will introduce the learner to
text mining and text manipulation basics. The
course begins with an understanding of how text
is handled by python”””

Visit : python.mykvs.in for regular


1. len() - length of the string argument
Eg: s = “Love” String Functions
len(s)
len(“Love”)
2. capitalize() – returns first letter capitalized
Eg: s = “love”
s.capitalize() #returns Love
3. count() – no of occurrences of the substring in
given string
Eg: s = “computer science”
s. count(‘e’) #returns 3
thisisatest’.count(‘is’,4) #returns 1 (4 –start)
‘thisisatest’.count(‘is’,6,10) #returns 0
0 1 2 3 4 5 6 7 8 9 10
T H I S I S A T E S T
4. find() – returns lowest index if found else -1
‘thisisatest’.find(‘is’) #returns 2
‘thisisatest’.find(‘is’,5,9) #returns -1
'thisisatest'.find(‘s’) #returns 3
5. index() - returns lowest index if found
else valueerror
‘thisisatest’.index(‘is’) #returns 2
‘thisisatest’.index(‘is’,5,9) #Valueerror.
'thisisatest’.index(‘s’) #returns 3
6. isalnum() – returns true if it is alphanumeric
str1,str2,str3,str4 = ‘345’,’py12’,’@#’, ‘ ‘
print(str1.isalnum(),str2.isalnum(),str3.isalnum(),
str4.isalnum()) #True True False False
7. isalpha() – returns true if the string is alphabetic
only
str1,str2,str3,str4 = ‘345’,’py12’,’@#’, ‘ ‘
print(str1.isalpha(),str2.isalpha(),str3.isalpha(),
str4.isalpha()) # False False False False
8. isdigit() – returns true if all the characters in
string are digits
print(str1.isdigit(),str2.isdigit(),str3.isdigit(),
str4.isdigit()) # True False False False
9. islower() – returns true if all the characters in
string are in lowercase # True False True
str1,str2,str3 = ‘aaa’,’345’,’aa12’
print(str1.islower(),str2.islower(),str3.islower())
9. isupper() – returns true if all the characters in string
are in uppercase
str1,str2,str3 = ‘aaa’,’AAA’,’Aaa’ # False True False
print(str1.isupper(),str2.isupper(),str3.isupper())
10. isspace() – returns true if they are only spaces
str1,str2,str3 = ‘ ‘, ‘a b’, “”
print(str1.isspace(),str2.isspace(),str3.isspace())

11. lower() – returns copy of the string in lowercase


str1,str2,str3 = ‘Ass’,’12a’,’eee’ # 'ass' '12a' 'eee'
print(str1.lower(),str2.lower(),str3.lower())
# 'ASS' '12A' 'EEE'
12. upper() – returns copy of the string in uppercase
print(str1.upper(),str2.upper(),str3.upper())
13. lstrip(),rstrip(),strip()
“ python”.lstrip() python
“python “.rstrip()
“ python “.strip()
14. startswith(), endswith() – returns true/false
“abcd”.startswith(“ab”) True
“abcd”.startswith(“cd”) False
“abcd”.endswith(“cd”) True
“abcd”.endswith(“ab”) False
15. title() – returns title case(first letter of each word)
of the given string This Is A Test
“this is a test”.title()
16. istitle() – returns true if string in title case
“This is a Test”.istitle() False
17. replace(old,new) – returns original/replaced
string
“Hello”.replace(“e”,”a”) # Hallo
“Hello”.replace(“a”,”e”) Hello
18. join() – joins a string/character between
members of the string
“*”.join(“Hello”) returns “H*e*l*l*o”
' '.join('This is a Test') returns 'T h i s i s a T e s t
19. split() – split given string and return list of
strings splitted
“I love python”.split()
returns [“I”,”love”,”python”]
“I love python”.split(“o”)
returns [“I l”,”ve pyth”,”n”]
20. partition() – Always split at first occurrence
and returns tuple of 3 items
1. part before separator
2. separator itself
3. part after separator
Eg
t = “I learn python”
t.partition(“learn”) (“I”,”learn”,”python”)

t.split(“learn”) [“I “,”python”]


t.split() [“I”,”learn”,”python” ]

t.partition(“ “) (“I “, ‘ ‘, ” learn python”)


Split() Partition()
Always returns list Always returns
of split substrings tuple of 3 members

Split() splits at every Partition only splits


occurrence of the based on first
given argument occurence

t="aeiouaeiou"
t.split("e")
['a', 'ioua', 'iou']
t.partition("e")
('a', 'e', 'iouaeiou')
reversed()

Returns an iterable object

reversed(“hello”)
<reversed object at 0x000002973BFB5990>

for i in reversed('Hello'):
print(i,end="")
1. Program to count no of uppercase, alphabets,
symbols, lowercase and no of digits
2. Program to count no of words in a given line
3. Program to count no of vowels in a given sentence
4. Python program to print even length words
in a string
5. Program to print the following pattern

INDIA
INDI
IND
IN
I

You might also like