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

Python Data Types and String Methods

The document provides an overview of Python's built-in data types including Sets, Lists, Tuples, and Dictionaries, highlighting their characteristics and usage. It also covers string manipulation techniques, including string methods, escape characters, and formatting. Additionally, it includes examples and code snippets for better understanding of these concepts.

Uploaded by

Swathi B S
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)
14 views26 pages

Python Data Types and String Methods

The document provides an overview of Python's built-in data types including Sets, Lists, Tuples, and Dictionaries, highlighting their characteristics and usage. It also covers string manipulation techniques, including string methods, escape characters, and formatting. Additionally, it includes examples and code snippets for better understanding of these concepts.

Uploaded by

Swathi B S
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

SETS :

 Collection of Elements
 Set items are unordered, unchangeable, and do not allow duplicate values.
 You cannot access elements using indexing like my_set[0]
 Set is one of 4 built-in data types in Python used to store collections of data, the other 3
are List , Tuple and Dictionary

Eg 1 : F = {1,3, 5,7,9,11, 13}


Eg 2 :
set = {"apple", "banana", "cherry"}
print(set)
Eg 3 :
my_set = {1, 2, 3} my_set.remove(2)
my_set.add(4) print(my_set)
print(my_set)
LIST :
A list is a value that contains multiple values in an ordered sequence
Mutable(changeable)
Defined using square bracket []
Values inside the list are also called items. Items are separated with commas
Each item in the list has an index, starting from ‘0’
Eg :
TUPLE :
 A tuple is an ordered, unchangeable (immutable) collection of data.
Tuples are immutable, meaning once a tuple is created, you cannot change, add,
or remove its elements.
Defined using parenthesis()
Eg :
RGB color code :
white = (255, 255, 255)
sky_blue = (0,191,255)
Eg :
Module 3
Dictionary and structuring Data
DICTIONARY :

 Dictionary is a collection of many values.


Defined in curly braces {}
Indexes for dictionaries are called keys, and a key with its associated
value is called a key-value pair.

Eg :
myCat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud’}
student = { ‘name’: ‘Alex’,‘student_id’: 451,‘courses’: [‘Math’, ‘Physics’, ‘CS’]}
The keys(), values(), and items() Methods
keys() Returns all the dictionary's keys.
values() Returns all the dictionary's values.
Items() Returns all the key:value pairs in the dictionary.
Eg :
Manipulating Strings
Working with Strings :
String Literals :
Standard (Single/Double Quoted) :
 The string begins with a double quote, Python knows that the single quote is part of the string
and not marking the end of the string.
Simple text, enclosed in
'Hello World' single quotes.
Eg : >>> spam = ‘That is Alice's cat.’
Simple text, enclosed in
O/P : Invalid "Python" double quotes.
>>> spam = "That is Alice's cat.” A sequence of digits
'12345' (treated as text, not a
O/P : That is Alice's cat. number).

However, if you need to use both single quotes and double quotes in the string, you’ll need to use
escape characters.
Escape Characters :
 An escape character lets you use characters that are otherwise impossible to put into a
string
 An escape character consists of a backslash (\) followed by the character you want to
add to the string.
 For example, the escape character for a single quote is \’.
>>> spam = 'Say hi to Bob\'s mother.’

Lists the escape characters :


Ex :

Raw Strings:
 A raw string completely ignores all escape characters and prints any backslash that appears in the
string.
Eg :

 Python considers the backslash as part of the string and not as the start of an escape character.
 Raw strings are helpful if you are typing string values that contain many backslashes
Multiline Strings with Triple Quotes :

 A multiline string in Python begins and ends with either three single quotes or three double quotes.
Eg :
print('''Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely,
Bob ''')
Eg :

poem = """
Roses are red,
Violets are blue,
This is a string
That spans line two.
"""
Multiline Comments :
 The hash character (#) marks the beginning of a comment for the rest of the line
 A multiline string is often used for comments that span multiple lines.
Eg :
Indexing and Slicing Strings

H E L L O W O R L D !

0 1 2 3 4 5 6 7 8 9 10 11

Eg : >>> spam = 'Hello world!’


>>> spam[0]
‘H’
Eg : 1 ) >>> spam[0:5] , spam[4] , >>>spam[-6] , >>> spam[6:], >>>spam[-1]
The in and not in Operators with Strings :

 The in and not in operators can be used with strings just like with list values.

 An expression with two strings joined using in or not in will evaluate to a


Boolean True or False.
Useful String Methods :
The upper(), lower(), isupper(), and islower() String Methods :
The upper() and lower() string methods return a new string where all the letters in
the original string have been converted to uppercase or lowercase
Eg :
>>> spam = 'Hello world!’
>>> spam = [Link]()
>>> spam
'HELLO WORLD!’
Eg :
>>> spam = [Link]()
>>> spam
'hello world!'
 The isupper() and islower() methods will return a Boolean True value
 If the string has at least one letter and all the letters are uppercase or
lowercase the method returns False.
Eg :
>>> spam = 'Hello world!’ >>> [Link]()
>>> [Link]() False
False

>>> 'HELLO'.isupper() >>> 'abc12345'.islower()


True True

>>> '12345'.islower() >>> '12345'.isupper()


False False
The upper() and lower() string methods themselves return strings

Eg :
>>> 'Hello'.upper()
'HELLO'
>>> 'Hello'.upper().lower()
'hello'
>>> 'Hello'.upper().lower().upper()
'HELLO'
>>> 'HELLO'.lower()
'hello'
>>> 'HELLO'.lower().islower()
True
The isX String Methods :
 isalpha() returns True if the string consists only of letters and is not blank.
 isalnum() returns True if the string consists only of letters and numbers and is not blank.
 isdecimal() returns True if the string consists only of numeric characters and is not blank.
 isspace() returns True if the string consists only of spaces, tabs, and newlines and is not blank.
 istitle() returns True if the string consists only of word that begin with an uppercase letter
followed by only lowercase letters.
• Eg : >>> 'hello'.isalpha() >>>'hello123'.isalnum() >>> 'This Is TitleCase'.istitle()
True True True

>>> '123'.isdecimal() >>> ' '.isspace() >>> 'This Is not Title Case'.istitle()
True True False
Write A program to validate the user input using X String methods
The startswith() and endswith() String Methods :
 The startswith() and endswith() methods return True if the string value they are
called on begins or ends (respectively) with the string passed to the method;
otherwise, they return False.
The join() and split() String Methods :
 The join() method is useful when you have a list of strings that need to be joined
together into a single string value.
The join() method is called on a string, gets passed a list of strings, and returns a
string. The returned string is the concatenation of each string in the passed-in list .
 The split() method does the opposite: It’s called on a string value and returns a
list of strings.
Eg :
Justifying Text with rjust(), ljust(), and center() :
 The rjust() and ljust() string methods return a padded version of the string they are
called on, with spaces inserted to justify the text.
 The center() string method works like ljust() and rjust() but centers the text rather than
justifying it to the left or right.
Eg :
Write a program to display the picnic items using rjust(), ljust(), and center() .

def printPicnic(itemsDict, leftWidth, rightWidth):


print('PICNIC ITEMS'.center(leftWidth + rightWidth, '-’))
for k, v in [Link]():
print([Link](leftWidth, '.') + str(v).rjust(rightWidth))
picnicItems = {'sandwiches': 4, 'apples': 12, 'cups': 4, 'cookies': 8000}
printPicnic(picnicItems, 12, 5)
printPicnic(picnicItems, 20, 6)
Removing Whitespace with strip(), rstrip(), and lstrip() :
The strip() string method will return a new string without any whitespace
The lstrip() and rstrip() methods will remove whitespace characters from the left
and right ends.
Eg :
Write a python program that accepts sentence and find the number of words , digits , uppercase and
lowercase letters
sentence = input("Enter a sentence:")
word = 0
digit = 0
lower = 0
upper = 0
words = [Link]()
word = len(words)
for char in sentence:
if [Link]():
upper = upper+1
elif [Link]():
lower = lower+1
elif [Link]():
digit = digit+1
print("Number of words is :", word)
print("Number of uppercase is :", upper)
print("Number of lowercase is :", lower)
print("Number of digit is :", digit)

You might also like