0% found this document useful (0 votes)
4 views26 pages

Class Xi Python Strings

Uploaded by

Manha Kar
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)
4 views26 pages

Class Xi Python Strings

Uploaded by

Manha Kar
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

STRINGS

Strings can be defined as a collection or sequence of character data enclosed in


quotes. The quotes can enclose numbers, characters, symbols etc. We have seen
string literals in earlier chapters. Now let’s take a look at how strings work in Python

Declaring a string
We can declare a string by simply assigning a variable to a string literal
How to Declare Python String?
a='Dogs are love'
a="Dogs are love"
How to Use Quotes inside Python String?
a='Dogs are "love"'
a="Dogs are 'love'"

Multiline strings
a="""Hello
Welcome"""


STRINGS
str="PyPlo
t“ Displaying a single character
To display a single character from
a string, put its index in square
brackets. Indexing begins at 0.
​Example:

>>> str="PyPlot"
>>> print(str[2])
P
A string is stored as an array with index values. In >>> print(str[-4])
python a string can be indexed in both directions. P
So for a string with n characters the indexing >>> print(str[-2])
would be like: o
​ >>> print(str[5])
0,1,2,3,4,.....n-1 -positive indexing t
-n,-n-1,.....4,3,2,1,0 -negative indexing
Traversing a String
​ Output:
We can use the for loop to traverse a string. C
​ o
Example: m
m
str1="Community" u
for i in str1: n
print(i) i
t
​for i in range(len(str1)): y
​ print(i)
print(s[i])

i=0
while(i<len(str)):
print(str[i])
i=i+1
PLAYING WITH STRING THRU
PROGRAMS

1)Program to count number of uppercase and lower case


letters in string

2)Program to find total no of characters , words and


sentences in a string.

3)Program to find whether substring exists in a string


STRING SLICING
Example: a="Dogs are love”
>>>print(a[3:8])
‘s are’
Here, it printed characters 3 to 7, with the indexing beginning at 0.
>>> a[:8]
‘Dogs are’
This prints characters from the beginning to character 7.
>>> a[8:]
‘ love’
This prints characters from character 8 to the end of the string.
>>> a[:]
‘Dogs are love’
This prints the whole string.
>>> a[:-2]
‘Dogs are lo’
This prints characters from the beginning to two characters less than
the end of the string.
>>> a[-2:]
‘ve’
This prints characters from two characters from the end to the end of
the string.
Let’s Try Ourselves
>>> s ='mybacon' >>> s ='mybacon‘

>>> s[2:] == s[2:len(s)]


>>> s[2:5]
True
'bac‘

>>> s[2:7] >>> s[:2] + s[2:]


'bacon' 'mybacon'
>>> s[0:2] >>> s[:]
'my' 'mybacon'

>>> s[:2] To get “noc” as output, write


'my‘ command
>>> s[:5] >>> s[-1:-4:-1]
'mybac‘ 'mybacon'
Numeric operators that work with Python
String
Concatenation is the operation of joining stuff together. Python Strings can
join using the concatenation operator +.
1.>>> a='Do you see this, '
2.>>> b='$$?'
3.>>> a+b
‘Do you see this, $$?’

Repeatition
Let’s take another example.
4.>>> a='10'
5.>>> print(2*a)
1010
Multiplying ‘a’ by 2 returned 1010, and not 20, because ‘10’ is a string, not a
number. You cannot concatenate a string to a number.
6.>>> '10'+10
Traceback (most recent call last):
File “<pyshell#49>”, line 1, in <module>
’10’+10
TypeError: must be str, not int
REVERSING STRINGS

Method1
Reversing a string
text = “Python”
Text1=“”
index = len(text) - 1
while index >= 0:
text1 += text[index]
index -= 1
print (text1)

Method2
Reversing through slicing
string_reversed = test_string[-1::-1]
print(string_reversed)

Method3
string_reversed = test_string[::-1]
print(string_reversed)
Strings are Immutable

Making changes to Strings Reassigning however


works sample_str =
This is not possible as strings are 'Programming String' print
immutable in Python. This means we (sample_str) #
cannot change any part of the string Output=> Programming String
or modify it.

Example:
>>> str="PyhtonPAndas"
>>> str[6]='t‘ Deleting a complete string works
del sample_str
Traceback (most recent call last): print
File "<pyshell#25>", line 1, in (sample_str)
<module> # NameError: name 'sample_str' is not defined
str[6]='t'
TypeError: 'str' object does not
support item assignment

https://towardsdatascience.com/immutable-vs-
mutable-data-types-in-python-e8a9a6fcfbdc
Python String Formatters

Sometimes, you may want to print variables along with a string. You can either use
commas, or use string formatters for the same.
1.>>> city='Ahmedabad'
2.>>> print("Age",21,"City",city)
Age 21 City Ahmedabad

i. f-strings
The letter ‘f’ precedes the string, and the variables are mentioned in curly braces in
their places.
3.>>> name='Ayushi'
4.>>> print(f"It isn't {name}'s birthday")
It isn’t Ayushi’s birthday
Notice that because we wanted to use two single quotes in the string, we delimited
the entire string with double quotes instead.
ii. format() method
You can use the format() method to do the same. It succeeds the string, and has the
variables as arguments separated by commas. In the string, use curly braces to posit
the variables. Inside the curly braces, you can either put 0,1,.. or the variables. When
doing the latter, you must assign values to them in the format method.
a=“dogs”
b=“kittens”
c=“puppies”
>>> print("I love {0}".format(a))
I love dogs
print("I love {0},{1},{2}".format(a,b,c))
I love dogs ,kittens , puppies

>>> print("I love {a}".format(a='cats'))


I love cats
The variables don’t have to defined before the print statement.
>>> print("I love {b}".format(b='ferrets'))
I love ferrets
Iii c. % operator
The % operator goes where the variables go in a string.
%s is for string.
What follows the string is the operator and variables in parentheses/in a tuple.
1.>>>
2.>>> print("I love %s and %s" %(a,b))
I love dogs and cats
Other options include:
%d – for integers
%f – for floating-point numbers

https://www.youtube.com/watch?
v=Bxr_ZYzC924
Python String
len() Functions
The len() function returns the length of a string.
1.>>> a='book' Islower()
2.>>> len(a) checks whether string is lower
4
Isupper()
str() checks whether string is upper
This function converts any data type into a string.
1.>>> str(2+3j)
‘(2+3j)’

lower() and upper()


These methods return the string in lowercase and uppercase,
respectively.
1.>>> a='Book'
2.>>> a.lower()
‘book’
3.>>> a.upper()
‘BOOK’
strip() isalpha()
It removes whitespaces from the Returns True if all characters in a string are
beginning and end of the string. characters from an alphabet.
1.>>> a=' Book ' 1.>>> a='abc'
2.>>> a.strip() 2.>>> a.isalpha()
‘Book’ True
lstrip() 3.>>> a='ab7'
rstrip() 4.>>> a.isalpha()
str = "---geeksforgeeks---“ False
print ( str.lstrip('-') )
print ( str.rstrip('-') ) isspace()
geeksforgeeks--- Returns True if all characters in a string are spaces
---geeksforgeeks 5.>>> a=' '
6.>>> a.isspace()
isdigit() True
Returns True if all characters in a 7.>>> a=' \' '
string are digits. 8.>>> a.isspace()
3.>>> a='777' False
4.>> a.isdigit()
True
5.>>> a='77a'
6.>>> a.isdigit()
False
find()
Find(value,start,end)
It takes an argument and searches
startswith()
for it in the string on which it is
It takes a string as an argument, and returns
applied. It then returns the index of
True is the string it is applied on begins with the
the substring.
string in the argument.
1.>>> 'homeowner'.find('meow')
1.>>> a.startswith('un')
2
True
If the string doesn’t exist in the
main string, then the index it
returns is -1.
endswith()
2.>>> 'homeowner'.find('wow')
It takes a string as an argument, and returns
-1
True if the string it is applied on ends with the
string in the argument.
count()
2.>>> a='therefore'
string.count(value, start,
3.>>> a.endswith('fore')
end)
True
txt = "I love apples, apple are my
favorite fruit“
x = txt.count("apple")
2
x = txt.count("apple", 10, 24)
1
replace()
It takes two arguments. The first is the substring to
be replaced. The second is the substring to replace
with.
1.>>> 'banana'.replace('na','ha')
‘bahaha’

The partition() method searches for a


specified string, and splits the string into a
tuple containing three elements. The first split()
element contains the part before the specified It takes one argument and by
string. The second element contains the default splits on occurrences of the
specified string. The third element contains white spaces. The string is then
the part after the string. split around every occurrence of
the argument in the string.
string = "Python is fun“ 1.>>> 'No. Okay. Why?'.split('.')
print(string.partition('is ')) [‘No’, ‘ Okay’, ‘ Why?’]
('Python ', 'is ', 'fun')
print(string.partition('not ')) "AB-CD-EF".split("-")
('Python is fun', '', '') ('AB','CD','EF')
numList = ['1', '2', '3', '4']
m. join()
separator = ', '
string.join(iterable)
print(separator.join(numList))
The join() method is a string method and returns a
string in which the elements of sequence have been
# .join() with tuples
joined by str separator.
numTuple = ('1', '2', '3', '4')
print(separator.join(numTuple))
>>> "*".join(['red','green','blue'])
‘red*green*blue’
s1 = 'abc'
s2 = '123'
Parameters: The join() method takes iterable –
objects capable of returning its members one at a
# each element of s2 is separated by s1
time. Some examples are List, Tuple, String,
# '1'+ 'abc'+ '2'+ 'abc'+ '3'
Dictionary and Set
print('s1.join(s2):', s1.join(s2))
Return Value: The join() method returns a string
concatenated with the elements of iterable.
# each element of s1 is separated by s2
Type Error: If the iterable contains any non-string
# 'a'+ '123'+ 'b'+ '123'+ 'b'
values, it raises a TypeError exception.
print('s2.join(s1):', s2.join(s1))
Capitalize()
title() method returns a title cased version of the
string. Meaning, the first character of each word is
Upper case the first letter in this sentence:
capitalized (if the first character is a letter).
txt = "hello, and welcome to my world."
text = 'My favorite number is 25.'
x = txt.capitalize()
print(text.title())
print (x)
My Favorite Number Is 25
OUTPUT
Hello, and welcome to my world.
Partition()
The partition() method splits the string at the first occurrence of the argument string and
returns a tuple containing the part the before separator, argument string and the part
after the separator.
The partition method returns a 3-tuple containing:
the part before the separator, separator parameter, and the part after the
separator if the separator parameter is found in the string
the string itself and two empty strings if the separator parameter is not
found
OUTPUT
string = "Python is fun" string = "Python is fun"

# 'is' separator is found # 'is' separator is found


print(string.partition('is ')) print(string.partition('is '))

# 'not' separator is not found # 'not' separator is not found


print(string.partition('not ')) print(string.partition('not '))

string = "Python is fun, isn't string = "Python is fun, isn't it"


it"
# splits at first occurence of 'is'
# splits at first occurence of print(string.partition('is'))
'is'
print(string.partition('is'))
Comparison
Python Strings can compare using the relational operators.
1.>>> 'hey'<'hi'
True
‘hey’ is lesser than ‘hi lexicographically (because i comes after e in the dictionary)
2.>>> a='check'
3.>>> a=='check'
True
4.>>> 'yes'!='no'
True
b. Arithmetic
Some arithmetic operations can be applied on strings.
5.>>> 'ba'+'na'*2
‘banana’
c. Membership
The membership operators of Python can be used to check if string is a substring to
another.
6.>>> 'na' in 'banana'
True
7.>>> 'less' not in 'helpless'
False
Identity
Python’s identity operators ‘is’ and ‘is not’ can be used on strings.
1.>>> 'Hey' is 'Hi'
False
2.>>> 'Yo' is not 'yo'
True
e. Logical
Python’s and, or, and not operators can be applied too. An empty string has a Boolean value
of False.
1. and- If the value on the left is True it returns the value on the right. Otherwise, the value
on the left is False, it returns False.
3.>>> '' and '1'

4.>>> '1' and ''

2. or- If the value on the left is True, it returns True. Otherwise, the value on the right
is returned.
3. not- As we said earlier, an empty string has a Boolean value of False.
5.>>> not('1')
False
6.>>> not('')
True
Programs ON Strings

1. Accept a string from the user and create another string made of
the first 2 and the last 2 chars from a given a string

2. Write a Python program to get a string made of the first 2


and the last 2 chars from a given a string. If the string
length is less than 2, return instead of the empty string.

3. Write a Python program to count Uppercase, Lowercase,


special character and numeric va
lues in a given string

4. Write a Python program to find smallest and largest word


in a given string

5. Write a Python program to capitalize first and last


letters of each word of a given string
Let’s Check out our
Knowledge

s = "python rocks"
print(s[1] * s.index("n")) yyyy
y

str = "His shirt is red"


pos = str.find("is") 1
print(pos)

string = "Python is awesome, isn't it?"


substring = "is"
1
count = string.count(substring,8,25)

You might also like