0% found this document useful (0 votes)
2 views13 pages

Python String

The document provides an overview of strings in Python, detailing their characteristics as immutable sequences of characters, and how to create and manipulate them. It covers string indexing, concatenation, replication, and various built-in functions and methods for string operations. Additionally, it includes examples of how to access characters, check for substrings, and modify strings using methods like upper(), lower(), and replace().

Uploaded by

angelasunil2008
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)
2 views13 pages

Python String

The document provides an overview of strings in Python, detailing their characteristics as immutable sequences of characters, and how to create and manipulate them. It covers string indexing, concatenation, replication, and various built-in functions and methods for string operations. Additionally, it includes examples of how to access characters, check for substrings, and modify strings using methods like upper(), lower(), and replace().

Uploaded by

angelasunil2008
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

Python Notes Class XI String

In Python a string is a collection of either ASCII characters or Unicode characters stored one variable name
in the RAM. However, string is a fundamental data type like int or float. A string is also called sequence,
and iterable type. A string similar to tuple rather than list since string is an immutable type. A string is created
in the following way:

strname='Kuwait' #creates a non-empty string


OR,
strname="Kuwait" #creates a non-empty string
OR,
strname='' #creates an empty string
OR,
strname="" #creates an empty string
OR,
strname=str() #creates an empty string

>>> str1='49 South Street, Ahamdi-61010, Kuwait'


>>> str2='शुभ भात'
>>> str3='সু ভাত'

String str1 contains ASCII characters and string str2 and str3 contains Unicode characters. However, will
work with strings that contains ASCII characters. A string is a sequence hence it supports index (both non-
negative and negative index). String is a homogeneous collection since it contains only characters (string with
single element). A string literal is enclosed with single quote (') or double quote (") or triple single quote (''')
or triple double quote (""").

Suppose str1 is string containing 'MANGO'

0 1 2 3 4 A string with 5 characters, characters


str1 M A N G O are assigned indices 0, 1, 2, 3, 4 or they
-5 -4 -3 -2 -1 are assigned indices -1, -2, -3, -4, -5.

>>> print(str1)
Displays the string str1 as MANGO. Kindly note, when a string displayed, the delimiters are not displayed.

How to access a character in a string? To access a character in a string we need to do the following:

strname[index]

Data type for index must be an int. If a string has n characters then indices are:
 0, 1, 2, …, n-3, n-2, n-1 Non-negative index
 -n, -(n-1), -(n-2), …, -3, -2, -1 Negative index
If index is out of range (access a character with an invalid index), will trigger a run-time error.

>>> str1='MNAGO'
>>> for k in range(5): print(str1[k],end=' ')
Displays the string left to right: M A N G O
>>> for k in range(1,5): print(str1[-k],end=' ')
Displays the string right to left: O G N A M
>>> for ch in str1: print(ch,end=' ')
Displays the string left to right: M A N G O
>>> print(str1[6])
>>> print(str1[-6])
Displays run-time error: string index out of range since a string has only 5 characters.
FAIPS, DPS Kuwait Page 1 of 10
Python Notes Class XI String
Using operators and keyword del with type
Creates a new string but cannot update a value stored in the string
>>> str1, str2='India, New Delhi', 'SONDAY'
>>> print(str1)
=
Displays India, New Delhi
>>> str1[1]='U'
Displays run-time error because the string is an immutable type.
Concatenate two or more strings
>>> str1='India,'+' New'+' Delhi'
+ >>> print(str1)
Displays India, New Delhi
Updates an existing string by concatenating another string
>>> str1='New'
>>> print(str1, id(str1))
+= Displays New, 2273046316016
>>> str1+=' Delhi'
>>> print(str1, id(str1))
Displays New Delhi 2273041112864 since string is an immutable type, ID changes
Replicate a string
>>> str1='Kuwait'
>>> print(str1*3)
Displays KuwaitKuwaitKuwait
>>> print(str1*0)
* Displays an empty string
>>> print(str1*-3)
Displays an empty string
>>> print(str1*2.5)
Triggers an error
A string can be multiplied with an integer value.
Updates an existing string by replicating values stored in the string
>>> str1='Delhi'
>>> str1*=3
*= The string str1 is updated triplicating values stored in the string.
>>> print(str1)
Displays DelhiDelhiDelhi
Deletes a string
>>> str1='Mangaf'
>>> del str1
>>> print(str1)
del
Displays run-time error because the string str1 has been deleted from the memory.
>>> str1='Mangaf'
>>> del str1[2]
Displays run-time error because the string is an immutable type.
Check whether a sub-string is a member of tuple
>>> str1='MANGAF'
>>> print('MAN' in str1, 'G' in str1)
in
Displays True True since 'ANG' and 'G' are present in the string str1
>>> print('GN' in str1)
Displays False since 'GN' is present in the string str1

Built-in functions for string data type


print()
As discussed earlier, function print() displays string on the screen without the delimiters.
FAIPS, DPS Kuwait Page 2 of 10
Python Notes Class XI String
len()
Function len() returns number of characters present in a string.
>>> str1,str2='FAIPS-DPS',""
>>> print(len(str1), len(str2))
Display 9 0

max(), min()
Function max() returns the character with highest ASCII code / Unicode from a string. Function min()
returns the character with lowest ASCII Code (Unicode) from a string.
>>> str1='FAIPS'
>>> print(max(str1), min(str1))
Display S A

sorted()
Function sorted() returns a list containing characters present in the string sorted in ascending order but
does not sort the characters present in the string. Using reverse=True returns a list sorted in descending
order.
>>> str1='FAIPS'
>>> sorted(str1)
Displays ['A', 'I', 'F', 'P', 'S']
>>> sorted(str1, reverse=True)
Displays ['S', 'P', 'I', 'F', 'A']
>>> print(str1)
Displays FAIPS

Methods from string objects:


Function name Use of the function of the function
Returns a string converted to uppercase. Only lowercase is converted to uppercase.
address='GH-14/783,Paschim Vihar,New Delhi-110087'
upper()
print([Link]())
Displays GH-14/783,PASCHIM VIHAR,NEW DELHI-110087
Returns a string converted to lowercase. Only uppercase is converted to lowercase.
lower(), address='GH-14/783,Paschim Vihar,New Delhi-110087'
casefold() print([Link]())
Displays gh-14/783,paschim vihar,new delhi-110087
Checks whether the string contains uppercase. Returns True if str does not contains any
lowercase. Returns False if a string contains lowercase.
isupper() a,b,c='FAIPS', 'FaIpS', 'PO BOX-9951'
print([Link](), [Link](), [Link]())
Displays True False True
Checks whether the string contains lowercase. Returns True if str does not contains any
uppercase. Returns False if a string contains uppercase.
islower() a,b,c='faips', 'fAiPs', 'po box-9951'
print([Link](), [Link](), [Link]())
Displays True False True
Checks whether the string contains either uppercase or lowercase. Returns True if a string
contains either uppercase or lowercase or both. Returns False if a string contains either
digits or special characters or both.
isalpha()
a,b,c,d='DPS','dps','DpS','PO Box-9951'
print([Link](),[Link](),[Link](),[Link]())
Displays True True True False
isdigit() Checks whether the string contains digit. Returns True if a string contains only digit.
Return False if a string contains either alphabets or special characters or both.
FAIPS, DPS Kuwait Page 3 of 10
Python Notes Class XI String
a,b,c,d='1234','FLAT24','flat24','Flat-24'
print([Link](),[Link](),[Link](),[Link]())
Displays True False False False
Checks whether the string contains either alphabet or digit or both. Returns True if a
string contains either alphabet or digit or both. Return False if a string contains special
characters.
isalnum()
a,b,c,d='Flat24','FLAT24','flat24','Flat-24'
print([Link](),[Link](),[Link](),[Link]())
Displays True True True False
Checks for whitespace characters space(' '), tab('\t') or new line('\n')
present in a string. A whitespace character is not visible on the screen. Returns True if a
isspace() string contains only whitespace character(s).
a,b,c,d=' ',' \t',' \t \n', 'New - Delhi'
print([Link](),[Link](),[Link](),[Link]())
Displays True True True False
Returns a string by converts the first character of a string to uppercase and rest of the
alphabetic characters are converted to lowercase.
str1,str2,str3='NEW DELHI','new delhi','NeW dElHi'
capitalize()
print([Link](), [Link](), end=' ')
print([Link]())
Displays New delhi New delhi New delhi
Return a string by converting first character of every word (sub string separated by white-
space character(s)) present in a string converted to uppercase, rest of the alphabetic
characters in the word will be converted to lowercase.
title()
str1,str2,str3='NEW DELHI','new delhi','NeW dElHi'
print([Link](),[Link](), [Link]())
Displays New Delhi New Delhi New Delhi
Exactly same as count() method of list and it returns occurrence of a sub-string present
within another string. Returns 0 (zero) if the sub-string could not be located in the string.
count() s='NEW DELHI'
print([Link]('E'),[Link]('DEL'),[Link]('IN'))
Displays 2 1 0
Almost similar to index() method list and it returns lowest non-negative index of a
sub-string present within another string. Unlike index() method of list, it returns -1
when the sub-string could not be located in the string.
s='NEW DELHI'
print([Link]('E'),[Link]('DEL'),[Link]('IN'))
find()
Displays 1 4 -1
print([Link]('E',4),[Link]('E',6))
Displays 5 -1
print([Link]('E'),[Link]('E',4),[Link]('E',6,10))
Displays 1 5 -1
Exactly similar to index() method list and it returns lowest non-negative index of a
sub-string present within another string. If a sub-string is not present in the string, it will
trigger a run-time error.
s='NEW DELHI'
print([Link]('E'),[Link]('DEL'),[Link]('E',4))
index()
Displays 1 4 5
print([Link]('D',2,7))
Displays 4
print([Link]('Z'))
Triggers a run-time error

FAIPS, DPS Kuwait Page 4 of 10


Python Notes Class XI String
Removes all the white-space characters from the both ends of a string.
s=' Mangaf, Kuwait '
strip()
print([Link]())
Display Mangaf, Kuwait removing white space characters from both ends
Removes all the white-space characters from the left (beginning) of a string.
s=' Mangaf, Kuwait '
lstrip()
print([Link]())
Display Mangaf, Kuwait removing white space characters from left
Removes all the white-space characters from the right (end) of a string.
s=' Mangaf, Kuwait '
lstrip()
print([Link]())
Display Mangaf, Kuwait removing white space characters from right
Creates a list containing sub-string from a string separated by white space character(s) by
default or separated by a delimiter. Delimiter is not included in the list.
s='Sun Mon Tue Wed Thu Fri Sat'
wlist=[Link]()
print(wlist)
Displays ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] since
parameter is missing from split() method, the default delimiter is white-space
s='Sun,Mon,Tue,Wed,Thu,Fri,Sat'
split()
wlist=[Link](',')
print(wlist)
Displays ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
s='FAIPS,DPS,Kuwait'
wlist=[Link]('*')
print(wlist)
Displays [FAIPS,DPS,Kuwait] since delimited '*' is missing, list contains only one
element, the entire string
The partition() method searches for a specified sub-string, and splits the string into a
tuple containing three elements. The first element contains the part before the specified
string. The second element contains the specified string. The third element contains the
part after the string.
s='MangafFahaheelAhmadi'
alist=[Link]('Fahaheel')
print(alist)
Displays ('Mangaf', 'Fahaheel', 'Ahmadi')
partition() alist=[Link]('Mangaf')
print(alist)
Displays ('', ' MangafFahaheel', 'Ahmadi')
alist=[Link]('Ahmadi')
print(alist)
Displays ('MangafFahaheel', 'Ahmadi', '')
alist=[Link]('Delhi')
print(alist)
Displays ('MangafFahaheelAhmadi', '', '')
The join() method takes all items (all items must be string) from an iterable (list / tuple /
dictionary) and joins them into one string. A string must be specified as the separator.
alist=['10','ASHOK','89.0']
blist=('21','ROOPA','75.5')
join()
astr=','.join(alist) #',' is the separator
bstr='~'.join(blist) #'~' is the separator
print(astr, bstr)
Displays 10,ASHOK,89.0 21~ROOPA~75.5
FAIPS, DPS Kuwait Page 5 of 10
Python Notes Class XI String
The replace() method replaces a specified phrase with another specified phrase.
s='ABCD , 1234 , efgh , {()}'
t=[Link](' , ', '<->')
replace() print(t)
Displays ABCD<->1234<->efgh<->{()}
By default replaces all occurrence of ' , ' with '<->'
The startswith() method returns True if the string starts with the specified value,
otherwise False.
s='Hello, Python'
startswith() print([Link]('Hell'), [Link]('Python'))
Displays True False
print([Link]('Python', 7))
Displays True
The endswith() method returns True if the string ends with the specified value, otherwise
False.
s='Hello, Python'
endswith() print([Link]('Hell'), [Link]('Python'))
Displays False True
print([Link]('Hell',0))
Displays True

#Obtain a new string by converting an inputted string into uppercase


astr=input('Input a string? ')
bstr=''
for ch in astr:
if 'a'<=ch<='z':
ch=chr(ord(ch)-32)
bstr+=ch
print('Uppercase string=',bstr)
OR,
astr=input('Input a string? ')
bstr=''
for x in range(len(astr)):
ch=astr[x]
if 'a'<=ch<='z':
ch=chr(ord(ch)-32)
bstr+=ch
print('Uppercase string=',bstr)

#Obtain a new string by converting an inputted string into lowercase


astr=input('Input a string? ')
bstr=''
for ch in astr:
if 'A'<=ch<='Z':
ch=chr(ord(ch)+32)
bstr+=ch
print('Lowercase string=',bstr)
OR,
astr=input('Input a string? ')
bstr=''
for x in range(len(astr)):

FAIPS, DPS Kuwait Page 6 of 10


Python Notes Class XI String
ch=astr[x]
if 'A'<=ch<='Z':
ch=chr(ord(ch)+32)
bstr+=ch
print('Lowercase string=',bstr)

#Obtain a new string by toggling the case of letters present in the


#inputted string
astr=input('Input a string? ')
bstr=''
for ch in astr:
if 'a'<=ch<='z':
ch=chr(ord(ch)-32)
elif 'A'<=ch<='Z':
ch=chr(ord(ch)+32)
bstr+=ch
print('Toggled string=',bstr)
OR,
astr=input('Input a string? ')
bstr=''
for x in range(len(astr)):
ch=astr[x]
if 'a'<=ch<='z':
ch=chr(ord(ch)-32)
elif 'A'<=ch<='Z':
ch=chr(ord(ch)+32)
bstr+=ch
print('Toggled string=',bstr)

#Obtain a new string by reversing the characters present in the inputted


#string
astr=input('Input a string? ')
bstr=''
for ch in astr: bstr=ch+bstr
print('Reversed String=', bstr)
OR,
astr=input('Input a string? ')
bstr=''
for x in range(len(astr)): bstr=astr[x]+bstr
print('Reversed String=', bstr)

#Check whether the inputted string is Palindrome or not


astr=input('Input a string? ')
bstr=''
for ch in astr:
bstr=ch+bstr
if astr==bstr:
print(astr, 'Palindrome')
else:
print(astr, 'Not Palindrome')
FAIPS, DPS Kuwait Page 7 of 10
Python Notes Class XI String
OR,
astr=input('Input a string? ')
bstr=''
for x in range(len(astr)):
bstr=astr[x]+bstr
if astr==bstr:
print(astr, 'Palindrome')
else:
print(astr, 'Not Palindrome')
OR,
astr=input('Input a string? ')
n=len(astr)
for x in range(n//2):
if astr[x]!=astr[-x-1]:
print(astr, 'Not Palindrome')
break
else:
print(astr, 'Palindrome')

#Count uppercase, lowercase, digits and special characters


astr=input('Input a string? ')
uc==lc=dc=sc=0
for ch in astr:
if 'A'<=ch<='Z': uc+=1
elif 'a'<=ch<='z': lc+=1
elif '0'<=ch<='9': dc+=1
else: sc+=1
print('Uppercase=', uc)
print('Lowercase=', lc)
print('Digit=', dc)
print('Special Characters=', sc)
OR,
astr=input('Input a string? ')
uc==lc=dc=sc=0
for x in range(len(astr)):
ch=astr[x]
if 'A'<=ch<='Z': uc+=1
elif 'a'<=ch<='z': lc+=1
elif '0'<=ch<='9': dc+=1
else: sc+=1
print('Uppercase=', uc)
print('Lowercase=', lc)
print('Digit=', dc)
print('Special Characters=', sc)

#Count uppercase, lowercase, digits white-space characters and special


#characters (excluding white-space characters
astr=input('Input a string? ')
uc=lc=dc=wc=sc=0
for ch in astr:
FAIPS, DPS Kuwait Page 8 of 10
Python Notes Class XI String
if 'A'<=ch<='Z': uc+=1
elif 'a'<=ch<='z': lc+=1
elif '0'<=ch<='9': dc+=1
elif ch in ' \t\n': wc+=1
else: sc+=1
print('Uppercase=', uc)
print('Lowercase=', lc)
print('Digit=', dc)
print('White-space Characters=', wc)
print('Special Characters=', sc)
OR,
astr=input('Input a string? ')
uc=lc=dc=wc=sc=0
for x in range(len(astr)):
ch=astr[x]
if 'A'<=ch<='Z': uc+=1
elif 'a'<=ch<='z': lc+=1
elif '0'<=ch<='9': dc+=1
elif ch in ' \t\n': wc+=1
else: sc+=1
print('Uppercase=', uc)
print('Lowercase=', lc)
print('Digit=', dc)
print('White-space Characters=', wc)
print('Special Characters=', sc)

#Counting words in an inputted string


astr=input('Input a string? ')
wlist=[Link]()
c1=c2=c3=c4=c5=c6=c7=0
for word in wlist:
if len(word)==4: c1+=1
if len(word)>4: c2+=1
if len(word)<4: c3+=1
if word[0] in 'AEIOUaeiou': c4+=1
if word[0] not in 'AEIOUaeiou': c5+=1
if word[-1] in 'AEIOUaeiou': c6+=1
if word[-1] not in 'AEIOUaeiou': c7+=1
print('Number of words with exactly 4 characters=', c1)
print('Number of words with more than 4 characters=', c2)
print('Number of words with less than 4 characters=', c3)
print('Number of words starting with vowel=', c4)
print('Number of words not starting with vowel=', c5)
print('Number of words ending with vowel=', c6)
print('Number of words not ending with vowel=', c7)

#Counting words containing at least two consonants


astr=input('Input a string? ')
wlist=[Link]()

FAIPS, DPS Kuwait Page 9 of 10


Python Notes Class XI String
wc=0
for word in wlist:
cc=0
for ch in word:
if 'A'<=ch<='Z' or 'a'<=ch<='z':
if ch not in 'AEIOUaeiou': cc+=1
if cc>1: wc+=1
print('Number of words containing at least 2 consonants=', wc)

FAIPS, DPS Kuwait Page 10 of 10


Python slice: is creating a subset from either a string or a list or a tuple. The concept of slice is valid for
list, string and tuple. How to create a slice?

A slice is created as var[beg:end:step]


var is the name of the list (tuple / string) variable
beg is the start index from where extraction of element start
end till end-1 index elements will be extracted
step is the step value

If beg is missing means starting index is 0 (zero). If end is missing means last idex is len(var)-1. If step is
missing, the default step value is 1. The concept of slice will be explained with a list of integers.
A list arr is created as: arr=[43, 79, 62, 15, 88, 57, 24, 36]

Positive Index 0 1 2 3 4 5 6 7
arr 43 79 62 15 88 57 24 36
Negative Index -8 -7 -6 -5 -4 -3 -2 -1

print(arr[2:6]) displays [62, 15, 88, 57]


Four (4) elements are displayed starting from index 2 and up to 5 (1 less than the beg). Since step is
missing, default step is 1. Step 1 mean every index starting from start index to last index (beg-1).
ar1=arr[2:6] will create a new list ar1 containing values 62, 15, 88 and 57.

print(arr[1:8:2]) displays [79, 15, 57, 36]


Start index is 1, step value is 2 => every second element starting from index 1 and end is 8 mean last
index is 7 (len(arr)-1).

print(arr[1:8:3]) displays [79, 88, 36]


Start index is 1, step value is 3 => every third element starting from index 1 and beg is 8 mean last index
is 7 (len(arr)-1).

print(arr[:5]) displays [43, 79, 62, 15, 88]


First 5 elements of the list are displayed. Beg is missing means starting index is 0, step is missing means
default step value is 1 and end is 5 means last index is 4.

print(arr[3:]) displays [15, 88, 57, 24, 36]


Last 5 elements of the list are displayed. Starting index is 5, step is missing means default step value is 1
and end is missing means last index is 7 (len(arr)-1).

print(arr[:7:2]) displays [43, 62, 88, 24]


Four (4) elements of the list are displayed starting from first element and skipping one. Beg is missing
means starting index is 0, step value is 2 means every second element, end is 7 means last index is 6.

print(arr[1::2]) displays [79, 15, 57, 36]


Four (4) elements of the list are displayed starting from second element (index 1) and skipping one.
Starting index is 1, step value is 2 means every second element, end index is missing means last index is
7 (len(var)-1).

print(arr[4:5]) displays [88]


Displays a list with single element whose index is 4. Start index is 4, default step value is 1 and beg is 5
means last index is 4.
print(arr[5:2]) displays []
An empty list is displayed. Start index is 5, default step value is 1 and end is 2, that is, beg exceeds end
with positive step value will create an empty list.

print(arr[5:5]) displays []
An empty list is displayed. Start index is 5, default step is 1 and end is 5 means last index is 4 (beg exceeds
end with positive step).

print(arr[5:2:-1]) displays [57, 88, 15]


Three (3) elements are displayed. Start index is 5, step is -1 and end is 2 means last index is 3 (one more
than end). Negative step value means sub-list will be created from right to left. Positive step value means
sub-list will be created from left to right.

print(arr[7:1:-2]) displays [36, 57, 15]


Three (3) elements are displayed. Display starts from index 7 then every second element from right to
left. Start index is 7, step is -2 and end is 1 means last index is 2 (one more than end).

Instead of positive beg and end, one can have negative beg and end as well. In Python list (tuple / string)
can have negative index.

print(arr[-6:-2]) displays [62, 15, 88, 57]


Four (elements are displayed starting from index -6. Start index is -6, step is missing means default step
is 1 and end is -2 means last index is -3 (end-1).

print(arr[-8:-1:2]) displays [43, 62, 88, 24]


Four (elements are displayed starting from index -8. Start index is -2, step is 2, and end is -1 means last
index is -2 (end-1).

print(arr[-4:-3]) displays [88]


Displays element with index -4. Start index is -4, step is missing means default index is 1, and end is -3
means last index is -4 (end-1).

print(arr[-4:-4]) displays []
Start index is -4, step is missing means default step value is 1, and end is -4 means last index is -5 (end-
1). With positive step value, beg exceeds end and hence empty list.

print(arr[-6:-7]) displays []
Start index is -6, step is missing means default step value is 1, and end is -7 means last index is -8 (end-
1). With positive step value, beg exceeds end and hence empty list.

print(arr[-2:-7:-1]) displays [24, 57, 88, 15, 62]


Five (5) elements are Displayed starting from index -2. Start index is -2, step is -1, and end is -7 means
last index is -8 (end-1). Negative step means sub-list will be displayed right to left.

print(arr[2:-2:]) displays [62, 15, 88, 57]


Four (3) elements are starting from index 2. Start index is 2, step is missing means default step is 1 and
end is -2 means last index is 6. What last index is 6? End is -2 (negative index) and equivalent positive
index is 7 means last index is beg-1 (7).

print(arr[0:-3:2]) displays [43, 62, 88]


print(arr[-8:5:2]) displays [43, 62, 88]
Four (3) elements are starting from index 0 (-8) every second element from left to right. Start index 0
(same as start index -8), step is 2 (every second element) and end is 5 means last index is 4 (beg-1). End
is 5 means equivalent negative index is -3.

print(arr[:]) displays [43, 79, 62, 15, 88, 57, 24, 36]
print(arr[::]) displays [43, 79, 62, 15, 88, 57, 24, 36]
Beg is missing means default start index is 0, end is missing means last index is len(arr)-1 and step is
missing means default step is 1.

print(arr[::-1]) displays [36, 24, 57, 88, 15, 62, 79, 43]
Displays the list in reverse order. Step is -1, means list will be displayed right to left. Beg is missing means
start index is len(arr)-1 and end is missing means last index is 0.

Python assignments base on Slice


1. Give the outputs of the Python programs given below:
a) mystr='FAIPSDPSKWT'
print(mystr[4:10])
print(mystr[2:11:2])
print(mystr[10:2])
print(mystr[8:2:-1])
print(mystr[11::-2])
print(mystr[0:11:-2])
print(mystr[-1:1])
print(mystr[1:-1])

b) mylist=[ 51, 61, 54, 93, 82, 74, 90, 81, 69, 72]
print(mylist[-9:-4])
print(mylist[-7:-2:-1])
print(mylist[-10::2])
print(mylist[2:-2])
print(mylist[1:-1:3])
print(mylist[::-2])
print(mylist[::3])
print(mylist[-1:-10:-2])

c) mytuple=( 656, 475, 231, 684, 240, 426, 297, 513, 638, 184)
print(mytuple[:-3])
print(mytuple[-3:])
print(mytuple[10:-2:-3])
print(mytuple[-6:-6])
print(mytuple[-4:7:2])
print(mytuple[10:-3:-2])
print(mytuple[4::-2])
print(mytuple[:10:-2])

You might also like