0% found this document useful (0 votes)
20 views50 pages

Strings

Uploaded by

sushma-icb
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)
20 views50 pages

Strings

Uploaded by

sushma-icb
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
You are on page 1/ 50

MODULE-3

1
Working with Strings
• String Literals :
Strings begin and end with a single quote. But then how can you use a quote inside a string?
Example - 'That is Alice's cat.'
This won’t work, because Python thinks the string ends after Alice, and the rest (s cat.')
is invalid Python code.
How do we overcome this problem ??

2
Using Double Quotes :
Strings can begin and end with double quotes, just as they do with single quotes.
One benefit of using double quotes is that the string can have a single quote
character in it.

3
Using 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.
• Example: the escape character for a single quote is \'. You can use this inside a string that begins and ends
with single quotes.

• Python knows that since the single quote in Bob\'s has a backslash, it is not a single quote meant to
end the string value.
• The escape characters \' and \“ let you put single quotes and double quotes inside your strings,
respectively.

4
Example :

5
Raw Strings
• We can place an r before the beginning quotation mark of a string to make it a raw string.
• A raw string completely ignores all escape characters and prints any backslash that
appears in the string.

• Because this is a raw string, 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,
such as the strings used for Windows file paths like r'C:\Users\Al\Desktop' or regular
expressions.
6
Multiline Strings with Triple Quotes

• A multiline string in Python begins and ends with either three single quotes or three double quotes.
• Any quotes, tabs, or newlines in between the “triple quotes” are considered part of the string.
• Python’s indentation rules for blocks do not apply to lines inside a multiline string.

What’s the output ??


Notice that the single quote
character in Eve's does not need
to be escaped.
Escaping single and double
quotes is optional in multiline
strings.
7
Indexing and Slicing Strings

• Strings use indexes and slices the same way lists do.
• Consider the string 'Hello, world!' as a list and each character in the string as an item
with a corresponding index.

• The space and exclamation point are included in the character count, so 'Hello, world!' is 13 characters
long, from H at index 0 to ! at index 12.
• By slicing and storing the resulting
substring in another variable, we can have
both the whole string and the substring
9
handy for quick, easy access.
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.

• These expressions test whether


the first string (the exact string,
case sensitive) can be found within
the second string.

10
Putting Strings Inside Other Strings

• Putting strings inside other strings is a common operation in programming. So far, we’ve
been using the + operator and string concatenation to do this:

However, this requires a lot of tedious typing.


How do this in a simpler way !

11
String Interpolation %s

• A simpler approach is to use string interpolation, in which the %s operator inside the
string acts as a marker to be replaced by values following the string.
• One benefit of string interpolation is that str() doesn’t have to be called to convert
values to strings.

12
F-string
• Python 3.6 introduced f-strings, which is similar to string interpolation except that braces
are used instead of %s, with the expressions placed directly inside the braces.
• Like raw strings, f-strings have an f prefix before the starting quotation mark.

• Remember to include the f prefix; otherwise, the braces and their contents will be a part
of the string value:

13
Useful String Methods : The upper(), lower(), isupper(), and islower() 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, respectively.
• Nonletter characters in the string remain unchanged.

• Note that these methods do not change


the string itself but return new string values.
• If you want to change the original string, you
have to call upper() or lower() on the string
and then assign the new string to the variable
where the original was stored.

14
• The upper() and lower() methods are helpful if you need to make a case insensitive comparison.
Example :
Consider the strings 'great' and 'GREat‘. They are not equal to each other.
But in the following small program, it does not matter whether the user types Great, GREAT, or grEAT,
because the string is first converted to lowercase.

So what’s the output

15
• The isupper() and islower() methods will return a Boolean True value if the string has at
least one letter and all the letters are lowercase and uppercase, respectively.
• Otherwise, the method returns False.

16
• Since the upper() and lower() string methods themselves return strings, we can call string
methods on those returned string values as well.
• Expressions that do this will look like a chain of method calls.

17
The isX() Methods

• isalpha() : Returns True if the string consists only of letters and isn’t 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 words that begin with an uppercase
letter followed by only lowercase letters
Note :
The isX() string methods are helpful when you need to validate user input. 18
19
Example : Validate Input

Output :

20
21
The startswith() and endswith() 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.

• These methods are useful alternatives


to the == equals operator if you need to
check only whether the first or last part
of the string, rather than the whole
thing, is equal to another string.

98
The join() Method

• 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.

• 23
The split() Method

• The split() method does the opposite of Join() method.


• It’s called on a string value and returns a list of strings.

• By default, the string 'My name is Simon' is split wherever whitespace characters such as
the space, tab, or newline characters are found.
• These whitespace characters are not included in the strings in the returned list.
• We can pass a delimiter string to the split() method to specify a different string to split
upon.
24
Example

25
Example

• A common use of split() is to split a multiline string along the newline characters.

• Passing split() the argument '\n' lets us split the multiline string stored in spam along the
newlines and return a list in which each item corresponds to one line of the string. 26
Python program to accept a string find the longest word and its length ( VTU Exam 6 Marks)

1. Read the input string from the user using the input function and store it in a string variable.
2. Pass the input string to longestWordLength method which finds the longest word and its length.
The returned values are stored in Maxword and Maxlength respectively.
3. Initialize the length of the longest word Maxlength to 0 and Initialize Maxword (longest word) to empty
4. Split the string into words using the splits function.
5. Compare the length of each word against the length Maxlength. If the length of the current word is more than the length
so far identified, replace the c with the length of the new word and Maxword with the new word.
6. Finally return the longest word Maxword and its length Maxlength.
7. Display the longest word and its length in the called function.

Expected Output :
Enter the string: Welcome back to college! We missed all of you in campus.
Longest word is college! and its length is 8
27
def longestWordLength(string):
Maxlength = 0 # Initilize length to 0
Maxword = '' # Initlize word to empty
# Finding longest word in the given sentence and word
for word in string.split():
if(len(word) > Maxlength):
Maxlength = len(word)
Maxword = word
return (Maxlength, Maxword)
string = input("Enter the string: ")  Start
l, w = longestWordLength(string)
print("Longest word is ", w, " and its length is ", l) 28
Splitting Strings with the partition() Method

• The partition() string method can split a string into the text before and after a separator
string.
• This method searches the string it is called on for the separator string it is passed, and
returns a tuple of three substrings for the “before,” “separator,” and “after” substrings.

29
• If the separator string passed to partition() occurs multiple times in the string that
partition() calls on, the method splits the string only on the first occurrence:

• If the separator string can’t be found, the first string returned in the tuple will be the
entire string, and the other two strings will be empty:

30
• We can use the multiple assignment trick to assign the three returned strings to three
variables:

• The partition() method is useful for splitting a string whenever you need the parts
before, including, and after a particular separator string.
31
Justifying Text with the rjust(), ljust(), and center() Methods

• 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 first argument to both methods is an integer length for the justified string.

• 'Hello'.rjust(10) says that we want to right-


justify 'Hello' in a string of total length 10.
• 'Hello' is five characters, so five spaces will
be added to its left, giving us a string of 10
characters with 'Hello' justified right.

32
• An optional second argument to rjust() and ljust() will specify a fill character other than a
space character.

• The center() string method works like ljust() and rjust() but centers the text rather
than justifying it to the left or right.

• These methods are especially useful when you need to print tabular data that
33
has correct spacing.
Example

34
Output :

35
Removing Whitespace with the strip(), rstrip(), and lstrip() Methods

• Sometimes we may want to strip off whitespace characters (space, tab, and newline)
from the left side, right side, or both sides of a string.
• The strip() string method will return a new string without any whitespace characters at
the beginning or end.
• The lstrip() and rstrip() methods will remove whitespace characters from the left and
right ends, respectively.

36
• Optionally, a string argument will specify which characters on the ends should be
stripped.

• Passing strip() the argument 'ampS' will tell it to strip occurrences of a, m, p, and capital S
from the ends of the string stored in spam.
• The order of the characters in the string passed to strip() does not matter: strip('ampS') will
do the same thing as strip('mapS') or strip('Spam').

37
Numeric Values of Characters with the ord() and chr() Functions

• Computers store information as bytes—strings of binary numbers, which means we need


to be able to convert text to numbers. Because of this, every text character has a
corresponding numeric value called a Unicode code point.
• For example, the numeric code point is 65 for 'A', 52 for '4', and 33 for '!'.
• We can use the ord() function to get the code point of a one-character string, and the
chr() function to get the one-character string of an integer code point.

38
• These functions are useful when you need to do an ordering or mathematical
operation on characters:

39
Copying and Pasting Strings with the pyperclip Module

• The pyperclip module has copy() and paste() functions that can send text to and receive
text from your computer’s clipboard.
• Sending the output of your program to the clipboard will make it easy to paste it into an
email, word processor, or some other software.
• The pyperclip module does not come with Python. To install it, follow the directions for
installing third-party modules.

40
41
42
Project: Adding Bullets to Wiki Markup

• When editing a Wikipedia article, you can create a bulleted list by putting each list item
on its own line and placing a star in front. But say you have a really large list that you want
to add bullet points to. You could just type those stars at the beginning of each line, one by
one. Or you could automate this task with a short Python script.

• So let us write code to get the text from the clipboard, add a star and space to the
beginning of each line, and then paste this new text to the clipboard.

43
Input :

Output :

This star-prefixed text is ready to be pasted into a Wikipedia article as a bulleted list.
44
Steps :

45
Step 1 : Paste text from the clipboard.

The call to pyperclip.paste() returns all the text on the clipboard as one big string.
If we used the “List of Lists of Lists” example, the string stored in text would look like this:

46
Step 2: Separate the Lines of Text and Add the Star

The \n newline characters in this string cause it to be displayed with multiple lines
when it is printed or pasted from the clipboard. There are many “lines” in this one string
value. You want to add a star to the start of each of these lines.

47
48
Step 3: Join the Modified Lines

49
Questions ?

50

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy