0% found this document useful (0 votes)
13 views54 pages

Strings Full

The document provides a comprehensive overview of string manipulation in Python, covering topics such as string literals, escape characters, raw strings, multiline strings, and various string methods. It also includes practical examples and projects, such as a password locker and a bullet point adder, demonstrating how to use the pyperclip module for clipboard operations. Additionally, it discusses string indexing, slicing, and methods for text justification and whitespace removal.

Uploaded by

ghthanushkumar
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)
13 views54 pages

Strings Full

The document provides a comprehensive overview of string manipulation in Python, covering topics such as string literals, escape characters, raw strings, multiline strings, and various string methods. It also includes practical examples and projects, such as a password locker and a bullet point adder, demonstrating how to use the pyperclip module for clipboard operations. Additionally, it discusses string indexing, slicing, and methods for text justification and whitespace removal.

Uploaded by

ghthanushkumar
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/ 54

STRINGS

By
Naveen Kumar .V
String Literals

Strings are collection of characters that begin and end with a


single quote.

But using a quote inside a string?

Typing 'That is Alice's cat.' won’t work,


because Python thinks 'That is Alice’s as string

and the rest (s cat.') is invalid Python code.


Fortunately, there are multiple ways to type strings

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.
Escape Characters

if you need to use both single quotes and double quotes in the
string, you’ll need to use 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.

The escape characters \' and \" let you put single quotes and
double quotes inside your strings, respectively.
Raw Strings

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

Will consider 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, mostly used for regular expressions
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.
Multiline Comments

While 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.
Indexing and Slicing Strings

Strings use indexes and slices the same way lists do. You can
think of 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,
'Hello world!' is 12 characters long, from H at index 0 to ! at
index 11.
If you specify an index, you’ll get the character at
that position in the string.

If you specify a range from one index to another,


the starting index is included and the ending
index is not. That’s why, if spam is 'Hello world!',
spam[0:5] is 'Hello'.

The substring you get from spam[0:5] will include


every-thing from spam[0] to spam[4], leaving out
the space at index 5.
Note that slicing a string does not modify the original string.
You can capture a slice from one variable in a separate
variable.

By slicing and storing the resulting substring in another


variable, you can have both
the whole string
the substring
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.
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, respectively.

Nonletter characters in the string remain unchanged.


Note :- These methods do not change the string itself but return
new string values.
To change the original string, you have to call
 upper() or lower() on the string
 then assign the new string to the variable where the original
was stored.

This is why you must use


spam = spam.upper() :- To change the string in spam
instead of simply spam.upper().

(This is just like if a variable eggs contains the value 10.


Writing eggs + 3 :- does not change the value of eggs,
but eggs = eggs + 3 does.)
The upper() and lower() methods are helpful if you need to
make a case-insensitive comparison.

The strings 'great' and 'GREat' are not equal to each other.
Here it does not matter whether the user types Great, GREAT,
or grEAT, because the string is first converted to lowercase.
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, respectively. Otherwise, the method
returns False.
Since the upper() and lower() string methods themselves return
strings, you can call string methods on those returned string
values as well.
Expressions that do this will look like a chain of method calls.
The isX String Methods

Along with islower() and isupper(), there are several string methods
that have names beginning with the word is.
These methods return a Boolean value that describes the nature of
the string.
Common 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 new-
lines 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.
The isX string methods are helpful when you need to validate
user input.
Eg:- This program repeatedly asks users for their age and a
password until they provide valid input.
Calling isdecimal() : - values in variables are decimal or not,
isalnum() :- values stored in alphanumeric or not.

Help us reject the input forty two and accept 42,


and reject secr3t! and accept secr3t.
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. Its
called on a string
gets passed a list of strings
returns a string.
The returned string is the concatenation of each string in the
passed-in list.
The string join() calls on is inserted between each string
of the list argument.

Eg:- when join(['cats', 'rats', 'bats']) is called on the ', ' string, the
returned string is 'cats, rats, bats’.

The split() method does the opposite: 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 white space characters are not included in the strings in the
returned list.

You can pass a delimiter string to the split() method to specify a


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


justified string.
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 useful when you need to print tabular
data that has the correct spacing.
Using rjust(), ljust(), and center() lets you ensure that strings
are neatly aligned, even if you aren’t sure how many characters
long your strings are.
Removing Whitespace with strip(), rstrip(), and lstrip()

Sometimes you 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.
Optionally, a string argument will specify which characters on
the ends should be stripped.

Passing strip() the argument 'ampS' will tell it to strip occurences 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').
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 to an email, word processor, or some other
software.
Of course, if something outside of your program changes the
clipboard contents, the paste() function will return it.

‘For example if I copied this sentence to the clipboard and then


called paste(), it would look like this: ’
Project: Password locker

You probably have accounts on many different websites.

It’s a bad habit to use the same password for each of them
( the hackers will learn the password to all of your other accounts)

It’s best to use password manager software on your computer that


uses one master password to unlock the password manager.

Then you can copy any account password to the clipboard and paste
it into the website’s Password field.
Step 1: Program Design and Data Structures

To run this program with a command line argument


 i.e the account’s name—for instance, email or blog.

That account’s password will be copied to the clipboard


 so the user can paste it into Password field.

Long, complicated passwords without having to memorize them.

You need to start the program with a


 #! (shebang) line
should also write a comment that briefly describes the program.
Step 1: Program Design and Data Structures

Associate each account’s name with its password :- dictionary.


Dictionary :- data structure that organizes your account and
password data.
Step 2: Handle Command Line Arguments

Command line arguments:- Stored in the variable sys.argv.


1st item in the sys.argv list :-program’s filename ('pw.py') and
2nd item should be the first command line argument.

For this program, this argument is :- account name


(whose password you want

Since the command line argument is mandatory


 Display a usage message to the user if they forget to add it
Step 3: Copy the Right Password

Once account name :-stored in the variable account,


check if it exists in PASSWORDS dictionary as a key.

If true :- copy the key’s value to clipboard using pyperclip.copy().


(Since you’re using the pyperclip module, you need to import it.)
That’s the complete script.
Code looks in the PASSWORDS dictionary for account name

If the account name is a key in the dictionary


Copy the value corresponding to that key to clipboard
print a message saying that we copied the value.
Otherwise
print a message saying there’s no account with that name.

You will have to modify the PASSWORDS dictionary value in the


source whenever you want to update the program with a new
password.
Project 2: 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.
 just type those stars at the beginning one by one
 could automate this task with a short Python script.
Step 1: Copy and Paste from the Clipboard

You want the bulletPointAdder.py program to do the following:


1. Paste text from the clipboard
2. Do something to it
3. Copy the new text to the clipboard

That second step is a little tricky.

but steps 1 and 3 are pretty straightforward:


They involve the pyperclip.copy() and pyperclip.paste() functions.
The TODO comment :- reminder that you should complete this
part of the program eventually.
The next step :- Actually implement that piece of the program.
Step 2: Separate the Lines of Text and Add the Star

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

You could write code that searches for each \n newline character
in the string and then adds the star just after that.

But it would be easier to use the split() method to return


 a list of strings, one for each line in the original string
 then add star to the front of each string in the list.
We split the text along its newlines to
get a list in which each item is one line of the text.
We store the list in lines and then loop through the items in lines.
For each line, we add a star and a space to the start of the line.
 Now each string in lines begins with a star.
Step 3: Join the Modified Lines

The lines list now contains modified lines that start with stars.
But pyperclip.copy() :-expecting a single string value, not a list
of string values.

To make this single string value,


 pass lines into the join() method
 to get a single string joined from the list’s strings.
Step 3: Join the Modified Lines
When this program is run,
it replaces the text on the clipboard :- text that has stars at the
start of each line.

Now the program is complete, and you can try running it with text
copied to the clipboard.

Even if you don’t need to automate this specific task,


you might want to automate some other kind of text manipulation,
removing trailing spaces from the end of lines
converting text to uppercase or lowercase.
Whatever your needs, you can use the clipboard for input and
output.
THE END

You might also like