[go: up one dir, main page]

0% found this document useful (0 votes)
13 views27 pages

Xi Cs Unit-2 Strings

This document provides an overview of strings in Python, including their definition, characteristics, and various operations such as concatenation, replication, and membership testing. It details built-in functions for string manipulation, indexing, and slicing, as well as methods for string comparison and transformation. The content is structured for a Class-XI Computer Science syllabus, focusing on computational thinking and programming.

Uploaded by

himankd61
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)
13 views27 pages

Xi Cs Unit-2 Strings

This document provides an overview of strings in Python, including their definition, characteristics, and various operations such as concatenation, replication, and membership testing. It details built-in functions for string manipulation, indexing, and slicing, as well as methods for string comparison and transformation. The content is structured for a Class-XI Computer Science syllabus, focusing on computational thinking and programming.

Uploaded by

himankd61
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/ 27

Class-XI CS

Unit-2: Computational thinking & Programming


Topic: Strings

Prepared By:
Mukesh Chourasia
PGT (Computer Science)
PM Shri Kendriya Vidyalaya No.2 CPE Itarsi
Strings

Syllabus:
 String introduction – Definition, examples, initializing, indexing,
traversing a string using loops.
 String operations – concatenation/joining, repetition/
replication, membership and slicing, List comparison
 built-in functions/methods: len(), capitalize(), title(), lower(),
upper(), count(), find(), index(), endswith(), startswith(),
isalnum(), isalpha(), isdigit(), islower(), isupper(), isspace(),
lstrip(), rstrip(), strip(), replace(), join(), partition(), split()
String: Introduction

Definition: A string is an ordered sequence of characters enclosed


with single (‘ ‘) or double(“ ”) or triple (‘’’ ‘’’) quotes.

Example:
S=‘India@Bharat’
Password=“abc#123”
mob=‘’’8975845885’’’
Address=“A/45, Preet vihar, New Delhi”
Characteristics of a String

 Each character has an index(also called subscript).


 Index of first character is 0 and the last character is n-1,
where n is number of characters in the string. (negative index
can also be used)
 Strings are immutable sequences i.e. they cannot be modified.
Creating/Initializing a String

There are two types of strings in python:


 Single line strings- written in single or double quotes
>>>S=“Hello, how are you?”
>>>L
Hello, how are you?

 Multiline strings- Written in triple single or triple double


quotes (or adding a backslash at the end of each line)
>>>S=‘’’Hello,
how are
you?’’’
>>>L
Hello,
how are
you?
Initializing means-assigning value directly to a String
Creating a String from user input

input() function is used to take a String as input from the user


Example:
Name=input(“Enter your name: ”)
print(“Hello: ”, Name)
Enter your name: Sunidhi
Hello: Sunidhi
Note: input() function by default takes user input as string.
String Indexing

There are two ways in which a String can be indexed


1. Forward indexing: 0 to n-1 (Left to Right)
2. Backward indexing: -1 to –n (Right to Left)
(Here, n is the no. of characters in the string)
Example: S=“Computer Science”

Elements in a list are accessed using index


Syntax
S[index]
Accessing characters in a String using index

Case1. if index is present in the string


Example: Given a String S, print the third character of the string
S=“Computer Science”
print(S[2]) # third character is at index=2
‘m’
Case2. if index is not present in the string
Example: In the above string, print the 20th character
print(S[19]) #20th character=> index=19
since the String
contains only 16
elements i.e.
upto index=15,
indexError occurs

Note: Index of a character=Position of character-1, for example 2nd character is at index=1


String is immutable

Modification of string elements is not possible because string is an


immutable data type.
Example:
S=“Computer Science”
S[10]=‘t’
String Traversal (Using for loop)

Traversal means going through the characters of the string from


either direction i.e. from left to right or from right to left
String Traversal (Using for loop & range function)

range(n) generates values from 0 to n-1


String Operations

Concatenation : Joining two Strings


Two strings can be concatenated(joined) using the concatenation
operator ’+’
Example:

Note: A string can be concatenated only with another string and not with any other
data type
String Operations

Replication : Repetition of strings


When a string is multiplied with a number using replication operator
’*’, it gets repeated as many times as the number.
Example:
>>>“India”*4
‘IndiaIndiaIndiaIndia’
>>>5*”20”
‘2020202020’
>>>”2”*”3” #two strings cannot be multiplied with each other
String Operations

Membership : Testing for membership in a string


Membership operators: in / not in are used to test whether a
substring is present in the string or not
in Results to True, if a value is found in a sequence, else returns False

not in Results to False, if a value is found in a sequence, else returns True


ASCII Codes

ASCII: American Standard Code for Information Interchange

ASCII values of characters are used for comparing two strings.

ord() and ch() functions-


ord()- function is used to get the ASCII value of a character
chr()- function is used to get the equivalent character of an
ASCII value.
String Operations

Comparison : Returns Boolean True or False


Relational operators are used: >,>=,<,<=,==,!= for comparison of two strings.
Elements of
the string are
compared one
by one.

TypeError: A sting can be


compared only with a string but
cannot be compared with any
other data type
String Slice

Syntax
S[Start:Stop:Step]
 Slicing a string creates a sub-string of the original string.
 The elements of the slice are from start index upto stop-1
index.
 Step value is optional & its default value is 1.
>>>S=“I love my country!”
>>>S
‘I love my country!’

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

I L o v e m y c o u n t r y
-17 -16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Both positive index and negative index can be used in slicing. Negative index starts
with -1 on the right upto –n on the left.
String Slice

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

I L o v e m y c o u n t r y
-17 -16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Start index must


be at the left &
stop index at the
right (if step value
is positive)

slice is reverse of
the original string
String Slice

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

I L o v e m y c o u n t r y
-17 -16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Start index must be


at the left & stop
index at the right (if
step value is
positive

Start index must


be at the right &
stop index at the
left (if step value
is negative)
String Methods & Built-in Functions
Method Description Example
len() counts the number of >>>S=‘India’ >>>S=‘’ #empty string
characters in the given string >>>len(S) >>>len(S)
5 0
>>>S=“Hello there!”
>>>len(S)
12
capitalize() returns a copy of the string >>>S=‘t20 World Cup’ >>>S=‘session-2025’
with its first character >>>S.capitalize() >>>S.capitalize()
capitalized, all other ‘Session-2025’
‘T20 world cup’
characters in lower case

title() returns a copy of string with >>>S=‘SEASON - five’ >>>S=‘I love my country’
first character of each word >>>S.title() >>>S.title()
in upper case and all other ‘I Love My Country’
‘Season - Five’
letters in lower case

count() counts the number of times a >>>S=‘This is a string’ >>>S=‘Work is Worship’


specified substring appears in >>>S.count(‘s’) >>>S.count(‘Wor’)
a given string
3 2
>>>S.count(‘p’)
0
String Methods & Built-in Functions
Method Description Example
find() returns the index where the >>>S=‘This is a string’ >>>S=‘Work is Worship’
substring first appears in the
>>>S.find(‘s’) >>>S.find(‘Wor’)
string or between two indexes.
Returns -1 if not found 3 0
>>>S.find(‘s’, 4, 15) >>>S.find(‘wor’)
6 #index 4 to 15 -1 #not present
index() returns the index where a >>>S=‘I love my country’ >>>S.index(‘you’)
substring is first found. >>>S.index(‘y’) ValueError:
returns ValueError if not found
8 substring not found
>>S.index(‘my’)
7
upper() returns a copy of string converted >>>S=‘India-2025’ >>>S=‘2025’
to upper case >>>S.upper() >>>S.upper()
‘INDIA-2025’ 2025
lower() returns a copy of string converted >>>S=‘World Cup-2025’ >>>S=‘2025’
to lower case >>>S.lower() >>>S.lower()
‘world cup-2025’ 2025
String Methods & Built-in Functions
Method Description Example
islower() returns True if all characters in >>>S1=‘T20’ >>>S3=‘2025’
the string are lowercase, False >>>S1.islower() >>>S3.islower()
otherwise False False
>>>S2=‘hello’ >>>S4=‘first name’
>>>S2.islower() >>>S4.islower()
True False
isupper() returns True if all characters in >>>S1=‘T20’ >>>S3=‘2025’
the string are uppercase, False >>>S1.isupper() >>>S3.isupper()
otherwise False False
>>>S2=‘HELLO’ >>>S4=‘FIRST NAME’
>>>S2.isupper() >>>S4.isupper()
True False
isspace() returns True if all characters in >>>S1=‘ ’ >>>S3=‘India’
the string are whitespaces, False >>>S1.isspace() >>>S3.isspace()
otherwise
True False
>>>S2=‘’ >>>S4=‘First Name’
>>>S2.isspace() >>>S4.isspace()
False False
String Methods & Built-in Functions
Method Description Example
isdigit() returns True if all characters >>>S1=‘India-2025’ >>>S3=‘RJ45’
in the string are digits, False
>>>S1.isdigit() >>>S3.isdigit()
otherwise
False False
>>>S2=‘2025’
>>>S2.isdigit()
True
isalpha() returns True if all characters >>>S1=‘India’ >>>S3=‘First Name’
in the string are alphabets
>>>S1.isalpha() >>>S3.isalpha()
True False
>>>S2=‘T20’
>>>S2.isalpha()
False
isalnum() returns True if all characters >>>S1=‘India’ >>>S3=‘First Name’
in the string are either
>>>S1.isalnum() >>>S3.isalnum()
alphabets or digits or both
True False
>>>S2=‘T20’ >>>S4=‘Roll.No.’
>>>S2.isalnum() >>>S3.isalnum()
True False
String Methods & Built-in Functions
Method Description Example
split() splits the string at the specified >>>S1=“I love India!” >>>S1=“I-love-India!”
separator and returns a list. >>>S1.split() >>>S1.split(‘-’)
Default separator is space, other
[‘I’, ’love’, ’India!’] [‘I’, ’love’, ’India!’]
characters can also be used as
separator

partition() partitions the string into three >>>S1=“I love my country India !”
parts and returns a tuple. >>>S1.partition(‘my’)
1. portion before the substring
( ‘I love’, ‘my’, ‘country India !’ )
2. substring
3. portion after the substring
Note: partition() needs at least one argument
strip() returns a trimmed version of the >>>S1=‘ Know your country ’
string. Trimming is done only >>>S1.strip()
when cases are matched with any
‘Know your country’
of the characters in the
argument from both sides of the >>>S2=‘make in India’ >>>S2.strip(‘Indi’)
string. >>>S2.strip(‘aim’) ‘make in India’
‘ke in Ind’ >>>S2.strip(‘aMk’)
>>>S2.strip(‘amk’) ‘make in Indi’
‘e in Indi’
String Methods & Built-in Functions
Method Description Example
lstrip() returns a trimmed version of the >>>S1=‘ Know your country ’
string. Trimming is done only >>>S1.lstrip()
when cases are matched with any
‘Know your country ’
of the characters in the
argument from left side of the
>>>S2=‘make in India’ >>>S2.lstrip(‘India’)
string. >>>S2.lstrip(‘aim’) ‘make in India’
‘ke in India’ >>>S2.lstrip(‘am’)
>>>S2.lstrip(‘amk’) ‘ke in India’
‘e in India’
rstrip() returns a trimmed version of the >>>S1=‘ Know your country ’
string. Trimming is done only >>>S1.rstrip()
when cases are matched with any
‘ Know your country’
of the characters in the
argument from right side of the >>>S2=‘make in India’ >>>S2.rstrip(‘India’)
string. >>>S2.rstrip(‘aim’) ‘make in ’
‘make in Ind’ >>>S2.rstrip(‘make’)
>>>S2.rstrip(‘amk’) ‘make in Indi’
‘make in Indi’
String Methods & Built-in Functions
Method Description Example
replace() returns a string with a >>>S1=‘I love my country’
substring replaced with
>>>S1.replace(‘country’,’India’)
another substring
Syntax: ‘I love my India’
S.replace(‘substr1’, ‘substr2’)
>>>S2=‘I study in class 11. I love python!’
>>>S2.replace(‘I’, ‘We’)
‘We study in class 11. We love python!’
startswith() returns True if the string >>>S1=‘Python Programming Language’
starts with the given
>>>S1.startswith(‘P’)
substring
True
>>>S1.startswith(‘Pyt’)
True
>>>S1.startswith(‘python’)
False
endswith() returns True if the string >>>S1=‘Python Programming Language’
ends with the given substring
>>>S1.endswith(‘e’)
True
>>>S1.endswith(‘guage’)
True
>>>S1.endswith(‘Age’)
False
String Methods & Built-in Functions
Method Description Example
join() creates a string by joining a >>>S=‘I love my country’
substring to the end of each
>>>’$’.join(‘S’)
character of a string (except
last character) ‘I$ $l$o$v$e$ $m$y$ $I$n$d$i$a’
Syntax: >>>L=[‘I’, ‘Love’, ‘Python’]
S=substring.join(Seq)
>>>’*’.join(L)
Seq-can be sring, list or tuple
‘I*Love*Python’
>>>T=(‘I’, ‘Love’, ‘Python’)
>>>’#@’.join(T)
‘I#@Love#@Python’
swapcase() swaps uppercase letters to >>>S1=‘All is Well’
lowercase and vice-versa
>>>S1.swapcase()
‘aLL IS wELL’

You might also like