0% found this document useful (0 votes)
28 views

Module 2.1

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Module 2.1

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 22

MODULE 2

Strings and lists


TOPICS
String
• String traversal
• String slices and comparison with examples
• The string module
• Character classification
List
• List values
• Accessing elements
• List membership
• Lists and for loops
• List operations
• List slices
• List deletion
• Matrices
Tuples
• Mutability and tuples
• Tuple assignment
• Tuples as return values
• Tuple operations

Dictionaries
• operations and methods.
String
• A string is a sequence of characters enclosed by double quotes.
• Eg: “ abc”, ‘abc’
• A string is defined as a character array.
• String is a series of characters that occupy continuous memory.

A compound data type


• In python we have three data types: int, float, and string.
• Strings are qualitatively different from the other two because they are made
up of smaller pieces—characters.
• Types that contain smaller pieces are called compound data types.
• The bracket operator selects a single character from a string.
>>> fruits = "banana"
>>> letter = fruits[1]
>>> print letter
• The expression fruits[1] selects character number 1 from fruit.
• The variable letter refers to the result.
• When we display letter, we get : a
Length
• The len function returns the number of characters in a string:
• Return the length of the given string.
>>> fruits = "banana"
>>> len(fruits)
6
Eg : fruits = "banana"
length=len(fruits)
print (length)
Traversal and the for loop
String Traversal
• A lot of computations involve processing a string one character at a time.
• Often they start at the beginning, and continue until the end.
• This pattern of processing is called a traversal
• Example 1
• One way to encode a traversal is with a while statement:
fruits = "banana"
index = 0
while (index < len(fruits)):
letter = fruits[index]
print (letter)
index = index + 1
• Example 2
• using for loop
• for loop : Syntax
for variable in sequence:
print variable

fruits = "banana"
for char in fruits:
print (char)
>>> words = ['cat', 'window’,‘elephant’]
>>> for w in words:
print w, len(w)

cat 3
window 6
elephant 8
String concatenation
• The following example shows how to use concatenation and a for loop to
generate an abecedarian series.
• “Abecedarian” refers to a series or list in which the elements appear in
alphabetical order.
prefixes ="JKLMNOPQ" • The output of this
program is:
suffix = "ack" Jack
Kack
for letter in prefixes: Lack
print (letter + suffix) Mack
Nack
Oack
Pack
Qack
1. WAP to read a string & then print the string in the reverse order.
2. Write a program to read a string and to find the number of occurrences of a
character.
3. WAP to read a string & then find the length of the given string without using
string function.
4. WAP to check whether given string is palindrome or not.
5. Write a program to read 2 strings and to find whether they are same or not
6. Write a program to read 2 strings and to find length of those strings and
thereafter to concatenate those strings and to find the length of resultant string.
7.WAP to find the number of vowels in a given line of text.
8. WAP to count the number of words in a given line of text.
9. WAP to replace every space in a string with a Hyphen
10. Python program to print even length words in a string
11. Write a Python program that takes two strings entered by the user and prints
True if the first string appears as substring in the second.
12. Write a Python program to add “ing” at the end of a string. If the string already
ends with “ing” then add “ly”
String slices
• A segment of a string is called a slice.
• Selecting a slice is similar to selecting a character:
>>> s = "Peter, Paul, and Mary"
>>> print s[0:5]
Peter
>>> print s[7:11]
Paul
>>> print s[17:21]
Mary
• The operator [n:m] returns the part of the string from the “n-th”
character to the “m-th” character, including the first but excluding the
last.
• If you omit the first index (before the colon), the slice starts at the
beginning of the string.
• If you omit the second index, the slice goes to the end of the string.
• Thus:
>>> fruit = "banana"
>>> fruit[:3]
’ban’
>>> fruit[3:]
’ana’
• What do you think s[:] means?
>>> fruit[:]
"banana"
Strings are immutable
• It is tempting to use the [] operator on the left side of an assignment, with the
intention of changing a character in a string.
• For example:
greeting = "Hello, world!"
greeting[0] = ’J’ # TYPE ERROR!
print (greeting)
• Instead of producing the output Jello, world!, this code produces the runtime
error TypeError: object doesn’t support item assignment.
• Strings are immutable, which means you can’t change an existing string.
• The best you can do is create a new string that is a variation on the original:
>>> greeting = "Hello, world!"
>>> newGreeting = ’J’ + greeting[1:]
>>> print newGreeting

Looping and counting


• The following program counts the number of times the letter ‘a’ appears
in a string:
fruit = "banana"
count = 0
for char in fruit:
if char == ’a’:
count = count + 1
print count
The string module
• The string module contains useful functions that manipulate strings.
• We have to import the module before we can use it.
>>> import string
Function find

• To call it we have to specify the name of the module and the name of the
function using dot notation.
• The find() method returns -1 if the value is not found.
>>> fruit = "banana" import string
>>> index = str.find(fruit, "a") fruit = "banana"
>>> print (index) index = str.find(fruit, "a")
1 val=str.find("banana", "na")
print (val)
print (index)
Whitespace
>>> print (string.whitespace)
• Whitespace characters move the cursor without printing anything.
• They create the white space between visible characters (at least on white
paper).
• The constant string.whitespace contains all the whitespace characters,
including space, tab (\t), and newline (\n).
# import string library function Capitalise each word of the sentence:
import string >>> string.capwords("this is a test")
print(‘Hello’)
result = string.whitespace 'This Is A Test’
print(result) import string
print(string.whitespace)
a=string.capwords("this is a test")
print(‘world')
print (a)
Character classification
• It classify a string based on the characters it contains.
• Here are character classification methods:
• str.isalnum() - Checks whether the string consists of alphanumeric characters
• str.isalpha() - Checks whether the string consists of alphabetic characters
only.
• str.isdigit() - Checks whether the string consists of digits only
• str.isidentifier() * - Determines whether the target string is a valid identifier.
• iskeyword(<str>) *
• str.isprintable() - Check if all the characters in the text are printable
• str.isspace() - Check if all the characters in the text are whitespaces
• str.istitle() - Checks whether all the case-based characters in the string
following non-case based letters are uppercase and all other
case-based characters are lowercase.
• str.islower()
• str.isupper()
• str.isascii()

• import a function called iskeyword() from the module called keyword:


from keyword import iskeyword
y=iskeyword('and’)
print (y)

OUTPUT
TRUE
s = 'abc123'
p =s.isalnum()
print(p)
True

s = 'abc$123'
s.isalnum()
False

>>> s = 'a\tb'
>>> s.isprintable()
False
>>> s = 'a b'
>>> s.isprintable()
>>> s = 'a \n b'
>>> s.isspace()
False
>>> s = '\t\n '
>>> s.isspace()
True

>>> s = 'The Sun Also Rises'


>>> s.istitle()
True
>>> s = "Bob's Burgers!"
>>> s.istitle()
False

You might also like