Strings in Python

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

Strings in Python

CLASS 11
CBSE
What are Strings?

> Consecutive sequence of UNICODE characters (letter, number, special


character, whitespace, backslash)

 Enclosed by single „ „ or double “ “


Triple quotes „‟‟ „‟‟ used for strings that span multiple lines

 An empty string has 0 character. E.g


S1 = „ „
 Python doesn‟t support character type, these are treated as strings of
length one
 Strings are IMMUTABLE - content of the string cannot be changed
after it is created. For eg. S1 = „Shimla‟ #S1[2] = „p‟ #error
Creating Strings

0 1 2 3 4 5 6 7 8 9 10 11
H E L L O W O R L D !
-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Str1 = „HELLO WORLD‟


or
Str1 = “HELLO WORLD”

Str2 = „This is Meera‟s pen.‟ #error

When a string contains special characters such as quotes, we need to escape


them with a backslash „ \ „ in front of them

Str2 = „This is Meera\‟s pen.‟ #correct


Creating Strings

S1 = “Write an article on „A1‟ briefly”

S1 = „Write an article on “A1” briefly‟

S2 = “She said, “I don‟t know” ” #error

S2 = „She said, “I don\‟t know” „ #correct

> If there are both single and double quotes in the string, we need to escape
the quotes using \ character in front of them to indicate the special nature
of the character.
Creating Strings

*If the statement is very long, then it can be shifted to multiple lines with the line continuation
character ( \ ), but it shows the result in the same line

S1 = „I am Sam, I work in xyz \


I stay in Delhi‟
>>> Print(S1)
I am Sam, I work in xyz I stay in Delhi

*To display output in the next line, use ( \n )


S1 = „I am Sam, I work in xyz \n I stay in Delhi‟
>>> Print(S1)
I am Sam, I work in xyz
I stay in Delhi

*To escape the sequence, use ( \t )


* Multiline strings, use triple single or double quotes („‟‟ „‟‟) or (“”” “””)
S1 = „‟‟I am sonika ,
S1 = „Name\t Place \t Time‟ I work in xyz
>>> Print(S1) I stay in Delhi‟‟‟
>>> Print(S1)
Name Place Time
I am Sam,
I work in xyz
I stay in Delhi
Indexing in a String

0 1 2 3 4 5 6 7 8 9 10 11
H E L L O W O R L D !
-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Str1 = „HELLO WORLD!‟  Each character in a string is an


Print(Str1[0]) //output H Index or represented by a locker /
room number . The Index operator
Print(Str1[3]) //output L square brackets [ ] retrieves the
Print(Str1[-5]) //output O value
 Index value can be accessed from
Print(Str1[12]) // Index Error Left or Positive index starts from 0
Print(Str1 [3.5]) //3.5 is float, Type Error and ends with length-1, or
Right or Negative index starts from
-1 to the length of the string
Traversing a String

0 1 2 3 4 5 6 7
m y w o r l d
-8 -7 -6 -5 -4 -3 -2 -1

 Accessing / Iterating each index of a string using either for or while loop
a) Iterating through string using for loop
#output #backend
S1 = “my world”
m Print(index0)
For i in S1: y Print(1)
Print(i) Print(2) space
w Print(i)
o Print(i)
r Print(6)
l Print(7)
d
Traversing a String #output
m
y

0 1 2 3 4 5 6 7 w
o
m y w o r l d
r
-8 -7 -6 -5 -4 -3 -2 -1 l
d
b) Iterating through string using while loop
Loop runs till the condition index<len(S1) is true, #backend
Where index increments from 0 to len(S1) - 1 0<8 S1[0]
1<8 S1[1]
S1 = “my world” 2<8 S1[2]
3<8 S1[3]
index = 0 …………….
While index < len(S1): #index < 8 7<8 S1[7]
8<8 end
print(S1[index], end = “\n”)
index += 1 #index = index +1
Special String Operations
Operations Details Example
1) Concatenation String1 + String2 „Good ‟ + „Morning‟
• Adding two strings Good Morning #output
• Adding an integer value to a string leads to „Good „ + 2 #Error
TypeError „6‟ + „3‟ #63 output

2) Repetition String1 * no.ToMultiply „Hi ‟ * 3


• Creates a new string by repeating multiple Hi Hi Hi #output
copies of the same string „2‟ * „3‟ #Error
• Operand - One string and one integer „2‟ * 3 #222 output

3) Membership Checks whether a particular character exists in the >>>„H‟ in „Hello‟


given string or not True
(both operands in – returns true if substring exists in the given >>> „Y‟ in „Hello‟
should be of string string False
type) not in – returns true if substring does not exists in >>> „Y‟ not in „Hello‟
the given string True
Special String Operations
Operations Details Example
4) Comparison • Compare two strings using comparison S1=„tim‟
operators like >, <, >=, <=, ==, != through S2=„tie‟
ASCII/Unicode(Ordinal) Value >>>S1 == S2
• Compare the first element from each sequence, False
if they are equal it goes on to the next element >>>S1 > S2
True

5) String Slicing • Retrieve a subset of values, substring/Slice Example in next slide


using :
• String_name [start: end: step]
• Python return a slice of string falling between
the starting position till end-1
Special String Operations
0 1 2 3 4 5 6 7 8 9
S A V E M O N E Y
String_name [start: end: step]
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Example Description
>>>A=„SAVE MONEY‟ Start from 1
>>>A[1:3] End at 2 i.e. (3-1)
„AV‟
>>>A[ : 3] If start is missing, default start is 0
„SAV‟
>>>A[3: ] If end is missing, it will to till last index
„E MONEY‟
>>>A[ : ] Entire string
„SAVE MONEY‟
>>>A[-2 : ] Irrespective of the starting point, it will print from left to
„EY‟ right
>>>A[ : -2] End index will be -2-1 = -3
„SAVE MON‟
>>>A[ : :2] Started from index 0, with stepping of 2
„SV OE‟
String Methods and Built-In Functions

Python provides built-in pre defined functions to perform actions /


manipulations on strings
Syntax – stringobject/variable.functionName()
Syntax –functionName(stringobject/variable)
Function Meaning Syntax Example
len() Length of the string len(Str) S1=„world‟
(it calculates all space, len(S1)
special characters etc.) >>>5

capitalize() Returns with the first Str.capitalize() S1=„world‟


letter in uppercase S1.capitalize()
>>>World
replace() Replaces all the Str.replace(old, new) S1=„My world‟
occurrences of the old print(S1.replace(„My‟, „Your‟))
string with the new string >>>Your world
String Methods and Built-In Functions
Function Meaning Syntax Example
index() Search the first occurrence index(substring, start, S1=„Hello, how are you?‟
and return the lowest end) index(„Hello‟)
index of the substring >>>0
isalpha() Checks only for the Str.isalpha() S1=„Hello, how are you?‟
alphabets/letters and S1.isalpha()
return true >>>False
isalnum() Checks for alphanumeric Str.isalnum() S1=„Hello, how are you?‟
and return true. S1.isalnum()
Space, !, #,%,&,? Etc. >>>False
are not alphanumeric
isdigit() Returns true if string Str.isdigit() S1=„750645‟
contains only S1.isdigit()
digits/numbers >>>True
Count() Returns no. of times Str.count(substring, S1=„Hello, how are you? Hello‟
substring occurs. Incase, start, end) S1.count(„Hello‟)
start and end is not given, >>>2
then search starts from S1=„Hello, how are you? Hello‟
index 0 and ends at length S1.count(„Hello‟, 7, 25)
of the string >>>1
String Methods and Built-In Functions
Function Meaning Syntax Example
lower() Converts all the uppercase letters Str.lower() >>>S1=„Learn PYTHON‟
in the string into lowercase Print(s1.lower())
learn python #output
upper() Converts all the lowercase letters Str.upper() >>>S1=„Learn PYTHON‟
in the string into uppercase Print(s1.upper())
LEARN PYTHON #output
islower() Returns True is all the letters in Str.islower() >>>S1=„Learn‟
the string are in lowercase Print(s1.islower())
False #output
isupper() Returns True is all the letters in Str.isupper() >>>S1=„LEARN‟
the string are in upper case Print(s1.isupper())
True #output
lstrip() • Returns the string after Str.lstrip() >>>S1=„ Learn Python‟
removing spaces from the left Str.lstrip(chars) Print(s1.lstrip())
l stands for • chars specify the set of Learn Python #output
left characters to be removed from
the left, all the combinations >>>S1=„ Learn Python‟
of chars are removed Print(s1.lstrip(Le))
arn Python #output

Print(s1.lstrip(eL))
arn Python #output
String Methods and Built-In Functions
Function Meaning Syntax Example
rstrip() • Returns the string after Str.rstrip() >>>S1=„ Learn Python ‟
removing spaces from the Str.rstrip(chars) Print(s1.rstrip())
r stands for right Learn Python #output
right • chars specify the set of
characters to be removed >>>S1=„ Learn Python‟
from the right, all the Print(s1.rstrip(on))
combinations of chars are Learn Pyth #output
removed
Print(s1.rstrip(no))
Learn Pyth #output
strip() Returns the string after removing Str.strip() >>>S1=„ Learn Python ‟
the spaces from both left and Print(s1.strip())
right Learn Python #output

isspace() Returns True if string contains Str.isspace() >>>S1=„ ‟


only whitespace characters, else Print(s1.isspace())
False True #output
Join(sequence Returns a string in which the Str.join(sequence) >>>S1=„12345‟
) elements have been joined by a >>>s=„ – „
separator >>>s.join(S1)
„1-2-3-4-5‟
String Methods and Built-In Functions
Function Meaning Syntax Example
swapcase() • Converts and returns all Str.swapcase( >>>S1=„ PYthOn‟
uppercase characters into ) Print(s1.swapcase())
lowercase and vice versa pyTHoN #output
Split the given string using the Str.partition( >>>S1=„ Hardworkpays‟
partition(Sepa specified separator and returns a separator) S1.partition(„work‟)
rator) tuple with 3 parts (substring („Hard‟, „work‟, „pays‟) #output
before the separator, separator S1.partition(„ -‟ )
itself and substring after the („Hardworkpays‟ , „ „, „ „) #output
separator)
endswith() True if the given string ends with Str.endswith( >>>S1=„I love Python‟
the specified substring, else false substr) >>>S1.endswith(„Python‟)
True
>>>S1.endswith(„love‟)
False
startswith() True if the given string starts with Str.startswith >>>S1=„I love Python‟
the specified substring, else false (substr) >>>S1.startswith(„Python‟)
False
title() Returns the string with the 1st letter Str.title() >>>S1=„my name is python‟
of every word in uppercase and rest >>>S1.title()
in lowercase My Name Is Python
istitle() Returns True if string is properly Str.istitle() >>>S1=„ Learn Python ‟
„title-cased‟, else False Print(s1.istitle())
#first letter of every word in True #output
uppercase
String Methods and Built-In Functions
Function Meaning Syntax Example
find() • Search the first Str.find(sub, start, >>>S1=„my name is python‟
occurrence of the end) >>>pring(S1.find(„my‟)
substring. If the 0
substring is not found, >>>pring(S1.find(„n‟)
it returns -1 3
split() Breaks up a string at the Str.split([separato colors=„Red:Blue:Orange:Pink‟
specified separator and r, [maxsplit]]) print(colors.split(„ : „,2))
returns a list of substrings [„Red‟, „Blue‟, „Orange:Pink‟ ]
separator (Optional) - string splits at the specified separator.
If the separator is not specified, any whitespace (space, newline print(colors.split(„ : „,1))
etc..) string is a separator [„Red‟, „Blue:Orange:Pink‟ ]

maxsplit (optional) – defines the maximum number of splits.


The default value of maxsplit is -1, no limit on the number of splits print(colors.split(„ : „,5))
[„Red‟, „Blue‟, „Orange‟, „Pink‟ ]

print(colors.split(„ : „, 0))
[„Red:Blue:Orange:Pink‟ ]
String Methods and Built-In Functions

Characters are stored in integer value in the internal storage or memory of


the computer

Characters ASCII (Ordinal) Value


„0‟ to „9‟ 48 to 57
„A‟ to „Z‟ 65 to 90
„a‟ to „z‟ 97 to 122

Function Meaning Example


ord() Returns the ASCII/Unicode(ordinal) >>>ord(„b‟)
98

chr() Returns the character represented by >>>chr(66)


the inputted Unicode/ASCII „B‟
Statement Flow Control

Conditional - Set of statements which is executed on the basis of result of a condition.


Loop - Set of statements which is executed repeatedly, until the end condition is satisfied.
Both conditional and loop are compound statements (a group of statements executed as a unit).
Represented by colon :

A pass statement moves to the next statement in the flow of control.

Conditionals in Python
* if
* if-else
* if-elif
* nested if
* storing conditions
Statement Flow Control

Python supports below standard mathematical logical conditions:

● Equals: a == b
● Not Equals: a != b
● Less than: a < b
● Less than or equal to: a <= b
● Greater than: a > b
● Greater than or equal to: a >= b

These conditions can be utilized in a variety of ways in the if statement.


Statement Flow Control
Conditionals in Python

If
Syntax Flow Example
if age = 16
condition: limit = 25
if (age == 16):
statements print('Age is correct as
mentioned')
(s)
if (age < 25):
print('Below age')
if (age > 10):
print('Teen')

if (age <= limit):


print('Under age limit')
if (age >= limit): # will not
be printed because the
condition is FALSE
print('Above limit')
Statement Flow Control
Conditionals in Python

If…else

Syntax Flow Example


if # Python program to compare
condition:
between subject marks
history = 45
statements
science = 57
(s)
else : if (history > science):
print('History marks
statement( greater than Science')
s) else:
print('Science marks
greater than History')
If…elif Statement Flow Control
Conditionals in Python

Syntax Flow Example


if condition1: marks =
statements(s) int(input('Enter marks
elif from 0-50: '))
condition2:
if (marks<20):
statements(s)
print('Student
elif
Failed')
condition3:
elif (marks>20 and
statements(s)
marks<40):
else:
print('Student
statements(s)
passed with B Grade')
else:
print('Student
passed with A Grade')
Statement Flow Control

Loop - Set of statements which is executed repeatedly, until the end condition is
satisfied.
Both conditional and loop are compound statements (a group of statements executed as a unit).
Represented by colon :
Looping Statements - for , range(), while, loop else, nested loops

The general form of for loop

for <control variable> in <Sequence> :


Statements_to_repeat

#the control variable takes a different value on each iteration in the sequence.

For example ,

for tens in [10, 20, 30, 40] :


print(tens+5, end= „ “)

#output 15 25 35 45
Statement Flow Control
range() based for loop
For number based list, range() function can be used. Below are 3 ways to define a
range:
range(stop) #elements from 0 to stop-1, increment by 1
range(start, stop) #elements from start to stop-1, increment by 1
range(start, stop, step) #elements from start to stop-1, increment by step

For example:
range(5) > 0, 1, 2, 3, 4 for sq in range(3, 6) :
print(“Square of no. ” , sq , “is ”,
range(2, 10) > 2, 3, 4, 5, 6, 7, 8, 9 (sq**2)) #3^2 = 3*3
range(2, 10, 3) > 2, 5, 8
#
range(10, 2) > no value, start can‟t be sq = 3
greater than stop unless it is a decreasing seq Square of no. 3 in 9 #end of 1st
range(10, 2, -1) > 10, 9, 8, 7, 6, 5, 4, 3 loop
Sq = 4
Square of no. 4 in 16 #end of
#a program to print squares of numbers in the
2nd loop
range of 3 to 5 Sq = 5
for sq in range(3, 5) : Square of no. 5 in 25 #end of
print(“Square of no. ” , sq , “is ”, (sq**2)) 3rd loop
Statement Flow Control

While loop
Conditional loop that will repeat the instructions as long as a conditional remains true
(boolean True). When the expression becomes false, the program control passes to the
line after the loop-body.
The while loop is used when it is not possible to know in advance how many times
the loop will be executed, but the termination condition is known. It is an entry-
controlled loop.

For example:
#program to calculate the sum of numbers until the user enters zero
total = 0
number = int(input('Enter a number: ')) Sum of numbers => variable
#add numbers until number is zero => total
while number != 0: Number => 2 => total =
total += number # total = total + number number
#take integer input again 3 => total = total+number =
number = int(input('Enter a number: ')) 5
10 => 5+15
print('total =', total)

You might also like