0% found this document useful (0 votes)
22 views100 pages

Strings

Uploaded by

Saksham Goel
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)
22 views100 pages

Strings

Uploaded by

Saksham Goel
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/ 100

Strings

CLASS XI
INFORMATICS PRACTICES
In Python, Strings are arrays of bytes representing
Unicode characters.
Python even a single character is a string

my_string = 'Hello’
Introduction
to my_string = "Hello”

Strings my_string = '''Hello'’’

my_string = """Hello, welcome to

the world of Python"""


Accessing characters in a String
Every character of a string has a position number called index

Mystring=“Computer Science”

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

C O M P U T U T S C I E N C E
To access/print a particular character of a string use []

print(stringvariable[index])

Mystr=“Strings in Python”
Accessing print(Mystr[4])
characters in print(Mystr[7])
a String print(Mystr[len(Mystr]-1]

Write a statement to print "i"

print(s[25]) #Raises IndexError


+ Concatenation

• Needs two strings and joins both


• A=‘Hello’
Operations • B=‘Colleagues’
in • print(A+B)
Strings
* Repetition

• A=‘Hello’
• print(A*3) #HelloHelloHello
Operations in Strings
in
Membership - Returns True if a substring exists in the given string
print(“in” in “Pin”) True
print(“IN” in “pin”) False
print(“cs” in “c s”)
False
not in
Membership – Returns True if a substring does not exist in a given string
len()
• returns number of characters in a string

max() x
Built in • print(max('Maximum’))

functions min() a
with • print(min('boolean’))

Strings any() True


• print(any('special’))

any() True
• print(any('special’))
MOST STRINGS ARE
IMPORTANT IMMUTABLE
PROPERTY OF
STRINGS
AN EXTREMELY IMPORTANT Changes cannot
CONSIDERATION …..
STRING VARIABLE CANNOT be made to
BE CHANGED strings
an immutable object can’t be
changed after it is created.

Example
IMMUTABLE int, float, bool literals
DATA TYPES
Strings

tuples
IMMUTABLE SIMPLE DATA TYPES
print(id(10))
x=10
140457543596032
print(id(x)) 140457543596032
print(id(20)) 140457543596352
140457543596352
x=20
140457543596352
print(id(x))
y=20
print(id(y))
s="BRONZE MEDAL"

IMMUTABLE print(s[1]) #allowed


STRINGS
WHAT DOES s[1]='A' #not allowed
IT MEAN
TypeError: 'str' object does not
support item assignment
s='New Year'

Which of the print(s[4],s[6])


following
statements s='Happy New Year'
are not
s[1]='i' TypeError
correct
print(s[9]) IndexError
What do you think is the output?
s='new year'
a=id(s)
print(a,type(a))
Output
140130896553008 <class 'int'>
s='happy new year'
140130896553072
b=id(s)
False
print(b)
print(a==b)
Do you think both print statements
will give the same result?
s='hello'
print(id(s)) Output
s=s+'there' 139957288719472
139957288719728
print(id(s))
What is the output?
>>>example = "snow world"
>>>example[3] = 's'
>>>print(example)
Recap –
Answer the
following
TypeError
Strings are immutable
What is the output?
>>>example = "snow world"
Recap – >>>max(example),min(example),any(example)
Answer the
following

w ‘ ‘ True
Traversal means processing each
character

Traversal in
Strings
Traversal in Python is possible in two
ways
Character Index Iteration
Iteration
Character traversal
for i in stringvar: #here i is each character of the string
print(i)

String=“Windows 10”
for i in String:
print(i) #prints each character in separate line

String=“Windows 10”
for i in String:
print(i) #prints each character in separate line
Example question of Character
traversal
Write the number of uppercase and lowercase letters in a String

string=input(‘Enter the string’)


upper,lower=0,0
for i in string:
if(65=<ord(i)<=91):
upper+=1
elif(97=<ord(i)<=122):
lower+=1
print(upper,lower)
Dynamic typing of strings

Learning Traversal in strings: Character


Objective iteration and index iteration

Programs practice
What do you think is the output?
s='new year'
a=id(s)
print(a,type(a))
Output
140130896553008 <class 'int'>
s='happy new year'
140130896553072
b=id(s)
False
print(b)
print(a==b)
Do you think both print statements
will give the same result?
s='hello'
print(id(s)) Output
s=s+'there' 139957288719472
139957288719728
print(id(s))
What is the output?
>>>example = "snow world"
>>>example[3] = 's'
>>>print(example)
Recap –
Answer the
following
TypeError
Strings are immutable
What is the output?
>>>example = "snow world"
Recap – >>>max(example),min(example),any(example)
Answer the
following

w ‘ ‘ True
Traversal means processing each
character

Traversal in
Strings
Traversal in Python is possible in two
ways
Character Index Iteration
Iteration
Character traversal
for i in stringvar: #here i is each character of the string
print(i)

String=“Windows 10”
for i in String:
print(i) #prints each character in separate line

String=“Windows 10”
for i in String:
print(i) #prints each character in separate line
Example question of Character
traversal
Write the number of uppercase and lowercase letters in a String

string=input(‘Enter the string’)


upper,lower=0,0
for i in string:
if(65=<ord(i)<=91):
upper+=1
elif(97=<ord(i)<=122):
lower+=1
print(upper,lower)
Program to find the length of a
string without using len()
a=input()
c=0
for i in a:
c+=1
print('No of characters are',c)
Take an input and copy the string
character by character into a new string
s=input('Enter a new string')
news=''
for i in s:
news=news+i
print(news)
NOTE: Each time we are asked to make changes to a string it means
taking a new string and building it up
Write a program to convert the case
of every letter in a string
Notes: To Remember Strings are immutable

Take input s=input('Enter the string')


news=''
Initialize a new string to blank for i in s:
if(65<=ord(i)<=90):
Iterate in the input string
news=news+chr(ord(i)+32)
Check if upper case elif(97<=ord(i)<=122):
news=news+chr(ord(i)-32)
Add the lowercase character to the new string
else:
Check if lower case news=news+i
print(news)
Add the uppercase character to the new string

Else

Add the character to the new string


Write a program to take an input and
create a new string that removes
duplicate occurrence of each character
Example : life is beautiful should become life sbautu
Take a string
Initialize new string to blank
a=input()
Iterate in a string
s=''
Check if I IS THERE in the new string for i in a:
If it is not add it to the new string if(i not in s):
Else s=s+i
Do not add print(s)
Find the output
string='Make my String'
news=''
for i in string: Output
if(ord(i)%2==0): @@@@ @@ @tr@n@
news=news+i
else:
news=news+'@'
print(news)
Quick Recap –
Given an input string with the
combination of the lower and
upper case arrange characters
in such a way that all lowercase
letters should come first.
str1 = PyNaTive
yaivePNT
Solution
string=input('Enter a string')
lower=''
upper=''
for i in string:
if(ord(i)>=97 and ord(i)<=122):
lower=lower+i
elif(ord(i)>=65 and ord(i)<=90):
upper=upper+i
string=lower+upper
print(string)
Index traversal
Since index always begins from 0 to len(string)-1
To traverse using index we will run a loop from 0 to len(string)-1
for i in range(0,len(string)):
print(i, string[i])

Q) Print every character on even index

for i in range(0,len(string),2):
print(string[i])
Write a program to print all position
numbers where there is a vowel in a string
This question requires index traversal
Take in a string string=input('Enter a string')
for i in range(0,len(string)):
Start iterating through index if(string[i] in 'aeiouAEIOU’):
print('Vowel at',i)
Check if character at that index is a
vowel
If yes print index
Write a program to find if a string is
a Palindrome or not
s=input('enter something')
y=''
for i in s:
y=i+y
if y==s: s=input('enter something')
print('tis a palindrome') for i in range(0,len(s)//2):
else: if s[i]!=s[len(s)-i-1]:
print('not a palindrome ') print('not a pal’)
break
else:
print('tis a pal')
Find the output:
s='Mango'
for i in range(len(s)):
print(s[i]*i)

Output
a
nn
ggg
oooo
Find the output
s='python'
for i in range(0,len(s)):
for j in range(0,i+1):
print(s[j],end=‘’)
print() Output
p
py
pyt
pyth
pytho
python
Find the output
mystr="HARMONIOUS"
L = len(mystr)
str2='' Output
str3='' ahm$nooi$$
for i in range(0,L,2):
str2=str2 + mystr[i+1]+mystr[i]
for ch in str2:
if ch>='R' and ch<='U’:
str3+='$’
else:
str3+=chr(ord(ch)+32)
print(str3)
Chocolate Question
#This question will be done in a different
way later
Read two strings and check if string1 is prefix from the string2.
ForEg-
string1: ever
string2: evergreen
Output: prefix
String1: All
String2: Alchemist
Output: No
Chocolate Question
Algorithm string1=input('Enter the substring')
string2=input('Enter the main string’)
Take substring and string flag=True
Start matching each character of String and Substring for i in range(0,len(string1)):
upto the length of Substring if(string1[i]!=string2[i]):
flag=False
If there is any instance where character does not match break
break if(flag==True):
print('Prefix')
If the loop has been broken then Substring is not a prefix else:
Else substring is a prefix print('No')
Practice Question
Read two strings and check if string1 is prefix or postfix from
the string2.
If you copy from internet or have done advanced do not
use any string method or slicing. Any such response will
not win a chocolate
Negative Indexing in Python
Python also allows negative indexing of characters from Right to left

Mystring=“Computer”

-8 -7 -6 -5 -4 -3 -2 -1

C O M P U T E R
Find the output
Output
s='Strings are fun'
s
for i in range(-9,-1,2):
a
print(s[i])
e
f

s='Strings are fun'


for i in range(-2,-8,2): No Output
print(s[i])

s='Strings are fun'


for i in range(-3,-8,-2): f*e*a*
print(s[i],end='*')
Slicing in Strings
Slicing allows part of string to be extracted
It works like the range function and allowance sequences of characters to be generated
Specify the start index and the end index, separated by a colon, to return a part of the string.

For Example
s='Air Conditioner’
print(s[2:9])
Output
r Condi

#All characters from 2 to 8 are extract


Slicing in Strings – Important points
If the start is not mentioned default start is 0

If the stop is not mentioned default stop is len(string)-1

The step can be mentioned by another colon

The default step is +1

If the step is mentioned as -1 then default start is len(string)-1 and default stop is 0
-15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 Slicing
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

R o t t e n F r u i t 1 2 3

s='Rotten Fruit123' n Fruit123


print(s[5:])
Rotte
print(s[:5])
te
print(s[2:8:2])
print(s[::]) Rotten Fruit123
print(s[::-1]) 321tiurF nettoR
print(s[::-2])
31ir etR
Find the output
s='Apple 23'*3 Apple 23Apple 23Apple 23
print(s)

y=s[1::3]
pe3p Al2
print(y) 2
z=s[6:7]

print(z)
pple 2
a=s[-15:15]

print(a)
Practical Question : Ceaser Cipher
In Cryptography, a Caesar cipher is a very simple encryption techniques in which
each letter in the plain text is replaced by a letter some fixed number of positions
down the alphabet list in a cyclic manner. For example, with a shift of 3, A would be
replaced by D, B would become E, and so on.
The method is named after Julius Caesar, who used it to communicate with his
generals. ROT-13 ("rotate by 13 places").
Methods in
Strings Functions Methods
A function is not bound to Methods are bound to
any object objects
A method is a function
A function can work with Methods work implicitly with
that “belongs to” an
different kinds of arguments the objects they are created
object. for

For example Strings has


its own set of methods,
list has different set of
methods
To print all
methods of
an object
PRINT(DIR(STR)) #PRINTS ALL
METHODS OF STRINGS
String methods
capitalize() title() center() upper() lower() swapcase() count() EXERCISE

startswith() endswith() find() rfind() index() rindex() EXERCISE format()

isupper() islower() isalpha() isdigit() isdecimal() isspace() istitle() ljust()

rjust() join() replace() strip() lstrip() rstrip() split() rsplit()

splitlines() partition() rpartition()


capitalize()
Return a copy of the string with only its first character capitalized.

s='computer science' #1 capitalize will return the string after converting the first
print(s.capitalize()) #1 letter into upper case

print(s) #2 #Output
#2 string will not change because Strings are immutable
Computer science
print(id(s)) #6 computer science #3 Here s variable is being reset to a new string with first
140690212087608
s=s.capitalize() #3 letter capital
Computer science
print(s) #4 140690211755544
#4 Hence the id’s of statement 5 and 6 will be different
print(id(s)) #5

Back
title()
Return a titlecased version of the string: title() capitalize()
words start with uppercase characters Converts first Converts first
letter of every letter of first
all remaining cased characters are lowercase. word word
s='happy new year' Even if first letter Only works if the
print(s.title()) is not a letter, it first letter is a
y='2020ad is a year of sorts'
convert the first capital letter
print(y.title())
letter in the word

Output
Happy New Year
2020Ad Is A Year Of Sorts
Back
upper()
Return a copy of the string converted to uppercase.

s='computer science 083python'


print(s.upper())

#Output
COMPUTER SCIENCE 083PYTHON

Back
lower()
Return a copy of the string converted to lowercase.

s=‘ComPutER SciENCe’
print(s.lower())

#Output
computer science

Back
swapcase()
Return a copy of the string with uppercase characters converted to lowercase and
vice versa.

s=‘ComPutER SciENCe’
print(s.swapcase ())

#Output
cOMpUTer sCIencE

Back
center(width[, fillchar])
Return centered in a string of length width. s='Programming'
print(s.center(10,'*'))
Padding is done using the specified fillchar
#Output
Default is a space Programming

s='stars' s='Happy'
print(s.center(10,'*’)) y=s.center(20)
print(y,'*’)
#Output
**stars*** #Output
Happy *
Back
count()
Return the number of occurrences of substring sub in string S[start:end].
Optional arguments start and end are interpreted as in slice notation.

s='''We regret to inform you that 2020 is only halfway over,


#Output
even though it feels like it’s been going on for half a century.
2
This is year 2020. We need to be patient''' 2
print(s.count('half')) 3
print(s.count('it')) 1
print(s.count('is')) 0
print(s.count('We',5)) 1
print(s.count('we’))
print(s[2:].count('We'))
Back
Recap: WAP to count the frequency
of characters in a string.
s=input("Enter a string")
news=" "
for i in s:
if i not in news:
news= news+i
print(i, "comes ",s.count(i),"times in original string")
Recap Exercise 1 Methods
Find the output
str1="john,simon,aryan"
print(str1.count('n,'))
print(str1.title())
print(str1.capitalize())

#Output
2
John,Simon,Aryan
John,simon,aryan
Back
startswith(prefix[, start[, end]])
Return True if string starts with the prefix, otherwise return False
prefix can also be a tuple of prefixes to look for
With optional start, test string beginning at that position.
With optional end, stop comparing string at that position.

s='Christmas carols' #Output


print(s.startswith('Christ')) True
print(s.startswith(('Christ','Christain')))
print(s.startswith('christ',2)) False
False
Back
endswith(suffix[, start[, end]])
Return True if the string ends with the specified suffix, else False
suffix can also be a tuple of suffixes to look for.
With optional start, test beginning at that position.
With optional end, stop comparing at that position.

txt = "Hello, welcome to my world." #Output


False
x = txt.endswith("my world.", 5, 11)

print(x)
find(sub[, start[, end]])
Return the lowest index in the string where substring sub is found
Optional arguments start and end are interpreted as in slice notation.
Return -1 if sub is not found. print("abcdef".find("cd") == "cd" in "abcdef")

print("ccdcddcd".find("c"))
#Output
#Output False
0 print(‘ccdcddcd’.find(‘dcd’)
print("ccdcddcd".find("cd")) print(‘alphabets’,find(‘phe’)

#Output
#Output 2
1 -1
find(sub[,start[,end]]) part 2
Write a code to find the second occurrence of
‘India’ in the sentence ‘India is a South Asian
country. India comes from word Indus’ s=input('Enter the sentence')
sub=input('Enter the substring')
Modify the code such that it prints all the indexes pos=-1
of the word in a sentence. Take the word and for i in range(s.count(sub)):
sentence from the user pos=s.find(sub,pos+1)
print(pos)

s='India is a South Asian country. India comes from word Indus'


print(s.find('India',s.find('India')+1))

Back
rfind(sub [,start [,end]])
Return the highest index in the string where substring sub is found
Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.

txt='India is a South Asian country. India comes #Output


from word Indus' 32
x = txt.rfind("India")
print(x)
index(sub[, start[, end]] )
The find() method returns the lowest index of the substring if it is found in given string. If its is
not found then it returns -1.
Index is different because
◦ If substring exists inside the string, it returns the lowest index in the string where substring is
found.
◦ If substring doesn't exist inside the string, it raises a ValueError exception.

sentence = 'Python programming is fun.’


Substring 'is fun’:
result = sentence.index('is fun’)
19 Traceback (most recent call last):
print("Substring 'is fun':", result)
File "<string>", line 6, in result = sentence.index('Java')
result = sentence.index('Java’)
ValueError: substring not found
print("Substring 'Java':", result)
EXERCISE 2 (String Methods)
What will be the output of the following Python code? Output
* abcdef *
print('*', "abcdef".center(7), '*')
Output
2
print("xyyzxyzxzxyy".count('yy', 1))

Output
s='Strings and String Methods are important'
40
print(len(s)) 12
Strings And String
print(s.find('String')+s.rfind('String')) Methods Are
print(s.lower().title()) Important
Back
Class XI
STRINGS – SESSION 6,7,8
format()
The format() method formats the specified value(s) and insert them inside the string's
placeholder.
The placeholder is defined using curly brackets: {}.
The format() method returns the formatted string.

txt2 ="My name is {0}, I'am {1}".format("John",36) #Output


txt3 ="My name is {}, I'am {}".format("John",36) My name is John, I'm 36
txt1 ="My name is {fname}, I'am {age}".format(fname ="John", age =36) My name is John, I'm 36
print(txt2) My name is John, I'm 36
print(txt1)
print(txt3)
format()
s="he is {} and he is {} years old" #Output
he is Nell and he is 34 years old
print(s.format('Nell',34))

txt = "We have {:<8} chickens." #Output


print(txt.format(49)) We have 49 chickens.
#Instils 8 spaces

Back
Islower() isupper() isalpha() isalnum()
islower()
Check if all the characters in the text are in lower case
isupper()
Check if all the characters in the text are in upper case
isalpha()
Check if all the characters in the text are letters
Isalnum()
Check if all the characters are alphabets or digits
Example
txt ='CompanyX' txt ='COMPANY X'
x=txt.isupper() x=txt.isupper()
y=txt.isalpha() y=txt.isalpha()
z=txt.islower() z=txt.islower()
print(x,y,z) print(x,y,z)

False True False True False False

Back
isdigit(), isdecimal(), isspace(), istitle()
isdigit()
Check if all the characters in the text are digits
isdecimal()
check if all the characters in the unicode object are decimals (Meaning decimal number system)
istitle()
Check if each word start with an upper case letter
Isspace()
Checks if the character is a space or not
Example
txt ='125'
x=txt.isdigit() True
y=txt.isdecimal() True
False
z="Hello there".istitle() True
a='Hello 123'.istitle()
print(x,y,z,a)

Back
Let’s Revise:
WAP to count the number of uppercase, lowercase, digits , space and any special
characters in a string.
Eg: Self Test-12@11
Uppercase: 2
Lowercase:6
Spaces: 1
Special character: 2
Digits: 4
ljust() and rjust()
Returns Left or right justified version of strings
txt='Strings'
Strings are important
print(txt.ljust(20),'are important')
Strings************* are immutable
print(txt.ljust(20,'*'),'are immutable') &&&Strings are indexed
Strings can be sliced
print(txt.rjust(10,'&'),'are indexed')
print(txt.rjust(20),'can be sliced')

Back
join()

01 02 03 04
The join() method A string must be string.join(iterable) Needs atleast two
takes all items in specified as the element long
an iterable and separator. iterable
joins them into one
string.
Join() Examples
txt='Python'
txt='P'
print('*'.join(txt))
print('*'.join(txt))
print(txt.join('**'))
P*y*t*h*o*n P
*Python*

myTuple = ("John", "Peter", "Vicky") txt=[1,2,3]


x = "#".join(myTuple)
print(x) print('*'.join(txt))
Error Elements of a
John#Peter#Vicky sequence must be string
Exercise: Find the output
list1 = ['H&M', 'zara', 'Uniqlo']
a=''.join(list1)
#Output
b=' '.join(list1) H&MzaraUniqlo
c='10'.join(list1)
print(a)
H&M zara Uniqlo
print(b) H&M10zara10Uniqlo
print(c)

Back
oldvalue Required. The string to search for

newvalue Required. The string to replace the old value with

count Optional. A number specifying how many occurrences


of the old value you want to replace. Default is all
occurrences

Returns a string where a specified value is


replaced with a specified value
replace() string.replace(oldvalue, newvalue, count)
Example replace()
txt = "one one was a race horse, two two was one too."
x = txt.replace("one", "three")
print(x)
print(txt)

#Output
three three was a race horse, two two was three too.
one one was a race horse, two two was one too.
Back
Example replace()
txt = "one one was a race horse, two two was one too."
x = txt.replace("one", "three",2)
print(x)
print(txt)

#Output
three three was a race horse, two two was one too.
one one was a race horse, two two was one too.
Back
strip() lstrip() rstrip()
string.strip(characters)
Returns a trimmed version of the string
Remove spaces at the beginning and at the end of the string
Space is the default character to remove

characters Optional. A set of characters to remove


as leading/trailing characters
Example
txt=' To remove blank spaces ' txt='To remove any characters aT'
print(txt.strip()) print(txt.strip('T'))
print(txt.lstrip()+'check') print(txt.lstrip('T'))
print(txt.rstrip()) print(txt.rstrip('T'))

#Output #Output
To remove blank spaces o remove any characters a
To remove blank spaces check o remove any characters aT
To remove blank spaces To remove any characters a

Back
string.split(separator, maxsplit)

Splits the string at the specified separator, and returns a list

The split() method splits a string into a list.

Split() –
Important You can specify the separator, default separator is any whitespace.

method When maxsplit is specified, the list will contain the specified number of
elements plus one.

separator Optional. Specifies the separator to use when splitting the string.
By default any whitespace is a separator
maxsplit Optional. Specifies how many splits to do. Default value is -1,
which is "all occurrences"
split() Examples
txt='Split method is used extensively in Python' txt='Split method is used extensively in
l=txt.split() Python'

print(l) l=txt.split('l')
print(type(l)) print(l)
['Split', 'method', 'is', 'used', 'extensively', 'in', 'Python'] ['Sp', 'it method is used extensive', 'y in Python']
<class 'list'>

txt='Split method is used extensively in Python'

l=txt.split(' ',2) ['Split', 'method', 'is used extensively in Python']


print(l)
Exercise: Find the output
str1="save paper,save plants" str1="save paper,save plants"
str1.split('save') str1=str1.split('save')
print(str1) print(str1)
['', ' paper, ', ' plants'] ['', ' paper,', ' plants']

print('abcdefcdghcd'.split('cd')) ['ab', 'ef', 'gh', '']


print('abcdefcdghcd'.split('cd',0)) ['abcdefcdghcd']
print('abcdefcdghcd'.split('cd',1)) ['ab', 'efcdghcd']
Use of split() in Programming
Example 1 : To find number of words in
a string
txt=input()
l=txt.split()
print(len(l))

Who ate my cheese?


4
Example 2: Find all words in the
sentence beginning with upper case
HINT You can iterate in list just as in string.
Lists are indexed too

txt=input() #Output
l=txt.split() Paris is the Capital of France
for i in l: Paris
if(i[0].isupper()): Capital
print(i) France
Exercise: To find all 4 letter words
from a sentence
txt=input()
Iran is a country in Asia
l=txt.split() Iran
for i in l: Asia
if(len(i)==4):
print(i)
H.W- Practical List Q12

Write a program to read a string and print


i)Frequency of all charactersii) Word of highest length
iii) The string in title caseiv) Read full name as a string and print only
the initials.
Eg- Enter name: Mohan Das Karam Chand Gandhi
Output string M D K C Gandhi.

Back
RECAP
WAP to count the number of words in a
string which start with vowel characters.
splitlines()
Splits the string at line breaks and returns a list
string.splitlines(keeplinebreaks)
Same as split(‘\n’)

keeplinebreaks Optional. Specifies if the line breaks


should be included (True), or not (False).
Default value is not (False)
Example
txt = "Thank you for the music\nWelcome to the jungle"
x = txt.splitlines()
print(x)
y=txt.splitlines(True)

['Thank you for the music', 'Welcome to the jungle’]


['Thank you for the music\n', 'Welcome to the jungle']

Back
Returns a tuple where the string is parted into
three parts
The first element contains the part before the
specified string.
The second element contains the specified
string.
partition()
The third element contains the part after the
string.
This method search for the first occurrence of
the specified string.
string.partition(value)
value Required. The string to search for
('homo sapiens', '', '')

Examples partition()
txt='homo sapiens' txt='homo sapiens' txt='homo sapiens'
print(txt.partition(' ')) print(txt.partition('o')) print(txt.partition('S'))
#Output #Output #Output
('homo', ' ', 'sapiens') ('h', 'o', 'mo sapiens') ('homo sapiens’, ‘ ‘, '')

txt='homo sapiens'
print(txt.partition('h'))

#Output
('', 'h', 'omo sapiens')
Exercise : Find the output
s="a@b@c@d" print('cd'.partition('cd'))
a= s.partition("@") print('abef'.partition('cd'))
print(a)
b=s.split("@",3) #Output
print(b) ('', 'cd', '')
('abef', '', '')
#Output
('a', '@', 'b@c@d')
['a', 'b', 'c', 'd']

Back
rpartition()
Returns a tuple where the string is parted into three parts
The rpartition() method searches for the last occurrence of a specified string, and
splits the string into a tuple containing three element

txt='python is an interpreter based language python is dynamic


txt='homo sapiens' and has extensive library support'
print(txt.rpartition('python'))
print(txt.rpartition('o'))

('python is an interpreter based language ', 'python', ' is


('hom', 'o', ' sapiens') dynamic and has extensive library support')

You might also like