What Is The Meaning of Single Quote and Double Quotes in String
What Is The Meaning of Single Quote and Double Quotes in String
Typing 'That is Alice's cat.' won’t work, because Python thinks the string ends after Alice, and the rest (s
cat.') is invalid Python code.
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. However, if you need to use both single quotes and double quotes in the
string, you’ll need to use escape characters.
What are escape chracters expain
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.
>>> spam = 'Say hi to Bob\'s mother.'
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.
Python considers the backslash as part of the string and not as the start of an escape character.
Raw strings are helpful while 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.
print('''Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely, Bob''')
Output:
Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely,
Bob
H e l l o , w o r l d !
'0 1 2 3 4 5 6 7 8 9 10 11 12
>>> spam = 'Hello, world!'
>>> spam[0]
'H'
>>> spam[4]
'o'
>>> spam[-1]
'!'
>>> spam[0:5]
'Hello'
>>> spam[:5]
'Hello'
>>> spam[7:]
'world!'
'My name is Al. I am 4000 years old.' //%S is replaced by AI and 4000 respectively.
Skipping the f prefix; produces the braces and their contents as part of the string value:
>>> 'My name is {name}. Next year I will be {age + 1}.'
'My name is {name}. Next year I will be {age + 1}.'//{name} ,{age+1} put in output for skipping f prefix
The upper() : This method return a new string where all the letters in the original string have been
converted to uppercase
>>> spam = 'Hello, world!'
>>> spam = spam.upper()
>>> spam 'HELLO, WORLD!' // Nonletter characters in the string remain unchanged i.e , and !
lower() : This method return a new string where all the letters in the original string have been converted
to lowercase
>>> spam = spam.lower()
>>> spam 'hello, world!' // Nonletter characters in the string remain unchanged i.e , and !
The upper() and lower() methods are helpful if you need to make a caseinsensitive comparison.
i.e the strings 'great' and 'GREat' are not equal to each other.
The upper() and lower() methods are helpful if you need to make a caseinsensitive comparison.
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
Explain how upper() and lower() useful in making case insensitive comparison.
For example, the strings 'great' and 'GREat' are not equal to each other.
It does not matter whether the user types Great, GREAT, or grEAT, because the string is first converted
to lowercase.
print('How are you?')
feeling = input()
if feeling.lower() == 'great':
print('I feel great too.')
else:
print('I hope the rest of your day is good.')
entering a variation on great, such as GREat, will still give the output I feel great too.
Explain with example how the isX() string methods are helpful when you need to validate user input.
The following program repeatedly asks users for their age and a password until they provide valid input.
while True:
print('Enter your age:') //ask the user for their age
endswith():This method return True if the string value they are called on ends with the string passed to
the method; otherwise, they return False.
>>> 'Hello, world!'.endswith('world!')
True
>>> 'Hello, world!'.endswith('Hello, world!')
True
>>> 'abc123'.endswith('12')
False
Explain The join() and split() Methods
The join() method is called on a string, gets passed a list of strings, and returns a string.
join() is called on a string value and is passed a list value
>>> ', '.join(['cats', 'rats', 'bats']) // join(['cats', 'rats', 'bats']) is called on the ', ' string, the returned string
is 'cats, rats, bats'.
'cats, rats, bats'
>>> ' '.join(['My', 'name', 'is', 'Simon'])
'My name is Simon'
>>> 'ABC'.join(['My', 'name', 'is', 'Simon'])
'MyABCnameABCisABCSimon'
The split() method does the opposite: It’s called on a string value and returns a list of strings.
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.
>>> 'My name is Simon'.split()
['My', 'name', 'is', 'Simon']
the string 'My name is Simon' is split wherever whitespace characters such as the space, tab, or newline
characters are found.
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:
>>> 'Hello, world!'.partition('XYZ')
('Hello, world!', '', '')
i.e XYZ is not present in the string hence Before string is returned that is ‘Hello ,World!’ separator string
and after strings are empty.
the multiple assignment trick to assign the three returned strings to three variables
>>> before, sep, after = 'Hello, world!'.partition(' ')
>>> before 'Hello,'
>>> after 'world!'
The center() : centers the text rather than justifying it to the left or right.
>>> 'Hello'.center(20)
' Hello '
An optional second argument to rjust() and ljust() will specify a fill character other than a space
character.
>>> 'Hello'.rjust(20, '*') //instead of whitspace ***** is padded
'***************Hello'
>>> 'Hello'.ljust(20, '-')
'Hello---------------' //instead of whitspace ------------ is padded
These methods are especially useful when you need to print tabular data that has correct spacing.
Using rjust(), ljust(), and center() lets you ensure that strings are neatly aligned.
The strip() string method will return a new string without any whitespace characters at the beginning or
end.
>>> spam = ' Hello, World '
>>> spam.strip() // strip method called on ‘ Hello, World! ‘
'Hello, World' // stripped whitespaces on bothe sides
The lstrip() : method will remove whitespace characters from the left ends
>>> spam.lstrip()
'Hello, World '
rstrip(): method will remove whitespace characters from the left right ends,
>>> spam.rstrip()
' Hello, World'
a string argument will specify which characters on the ends should be stripped.
>>> spam = 'SpamSpamBaconSpamEggsSpamSpam'
>>> spam.strip('ampS')
'BaconSpamEggs'
//Passing strip() the argument 'ampS' will tell it to strip occurrences of a, m, p, and capital S from both
the ends of the string stored in spam.
The order of the characters in the string passed to strip() does not matter:
strip('ampS') , strip('mapS') or strip('Spam') all are same strip off a,m,p and S occurances before and
after.
1. Folder Path: the file folder location on the file system where subsequent folders
are separated by a forward slash / (Unix) or backslash \ (Windows)
2. File Name: the actual name of the file
3. Extension: the end of the file path pre-pended with a period (.) used to indicate
the file type
Backslash on Windows and Forward Slash on macOS and Linux On Windows, paths
are written using backslashes (\) as the separator between folder names. The macOS
and Linux operating systems,
Explain path()
the Path() function in the pathlib module, If you pass it the string values of individual file
and folder names in your path, Path() will return a string with a file path using the correct
path separators.
>>> from pathlib import Path
>>> Path('spam', 'bacon', 'eggs')
WindowsPath('spam/bacon/eggs')
If you want to get a simple text string of this path, you can pass it to the str() function,
which in our example returns 'spam\\bacon\\eggs'.
the / operator combine Path objects and strings. This is helpful for modifying a Path
object after you’ve already created it with the Path() function.
>>> from pathlib import Path
>>> Path('spam')
/ 'bacon' / 'eggs'
WindowsPath('spam/bacon/eggs')
>>> Path('spam') / Path('bacon/eggs')
WindowsPath('spam/bacon/eggs')
>>> Path('spam') / Path('bacon', 'eggs')
WindowsPath('spam/bacon/eggs')
To return the directory you are currently in, we use the OS module to interact with the
operating system. Under the OS module, we use the os.getcwd()) method to return the
path of the current directory.
You can get the current working directory as a string value with the Path.cwd() function
>>> from pathlib import Path >>> import os >>> Path.cwd()
WindowsPath('C:/Users/Al/AppData/Local/Programs/Python/Python37')'
change it using os.chdir()
>>> os.chdir('C:\\Windows\\System32')
>>> Path.cwd()
WindowsPath('C:/Windows/System32')
.
The Home Directory
A home directory is a file system directory on a multi-user operating system
containing files for a given user of the system.
(1) A storage folder that contains the user's personal files. Starting with Windows
Vista, the Windows home directory is \user\username.
(2) You can get a Path object of the home folder by calling Path.home():
(3) >>> Path.home()
(4) WindowsPath('C:/Users/Al')
Relative Paths
A relative path is the path that (as the name sounds) is relative to the working directory
location on your computer.
If the working directory is earth-analytics, then Python knows to start looking for your
files in the earth-analytics directory.
Following the example above, if you set the working directory to the earth-
analytics directory, then the relative path to access streams.csv would be:
data/field-sites/california/colorado/streams.csv
Data Tip The default working directory in any Jupyter Notebook file is the directory in
which it is saved. However, you can change the working directory in your code!
However, imagine that you set your working directory to earth-analytics/data which is a
subdirectory of earth-analytics.
The correct relative path to the streams.csv file would now look like this:
field-sites/california/colorado/streams.csv
Relative paths are useful if you can count on whoever is running your code to have a
working directory setup similar to yours. When the details of your directory setup are
shared with others who can replicate it, then you can use relative paths to support
reproducibility and collaboration.
Absolute Paths
An absolute path is a path that contains the entire path to the file or directory that you
need to access. This path will begin at the home directory of your computer and will end
with the file or directory that you wish to access.
/home/your-username/earth-analytics/data/field-sites/california/colorado/streams.csv
Absolute paths ensure that Python can find the exact file on your computer.
However, as you have seen, computers can have a different path constructions,
depending on the operating system, and contain usernames that unique to that specific
machine.
There are ways to overcome this issue and others associated with finding files on
different machines using tools such as the os package in Python.
Handling Absolute and Relative Paths
Calling the is_absolute() method on a Path object will return True if it represents an
absolute path or False if it represents a relative path.
>>> Path.cwd()
WindowsPath('C:/Users/Al/AppData/Local/Programs/Python/Python37')
>>> Path.cwd().is_absolute()
True
>>> Path('spam/bacon/eggs').is_absolute()
False
To get an absolute path from a relative path, you can put Path.cwd() / in front of the
relative Path object.
>>> Path('my/relative/path')
WindowsPath('my/relative/path')
>>> Path.cwd() / Path('my/relative/path')
WindowsPath('C:/Users/Al/AppData/Local/Programs/Python/Python37/my/relative/
path')
If your relative path is relative to another path besides the current working directory,
just replace Path.cwd() with that other path instead.
The following example gets an absolute path using the home directory instead of the
current working directory:
>>> Path('my/relative/path')
WindowsPath('my/relative/path')
>>> Path.home() / Path('my/relative/path')
WindowsPath('C:/Users/Al/my/relative/path')
Explain os.path module
The OS module is a function that allows interaction with the operating system. It is a
part of the standard utility modules of Python. This feature contains the functions to
fetch the information that is based on the local directories, processes, files, and
environmental variables.
The main functionality of this module includes merging, normalizing, and fetching the
path names in python. As this feature is useful in applying the function on paths, the
parameters of paths are passed either in the form of strings or bytes.
The os.path module also has some useful functions related to absolute and
relative paths:
• Calling os.path.abspath(path) will return a string of the absolute path of the argument.
This is an easy way to convert a relative path into an absolute one.
• Calling os.path.isabs(path) will return True if the argument is an absolute path and
False if it is a relative path.
• Calling os.path.relpath(path, start) will return a string of a relative path from the start
path to path. If start is not provided, the current working directory is used as the start
path.
Calling os.path.dirname(path) will return a string of everything that comes before the
last slash in the path argument.
Calling os.path.basename(path) will return a string of everything that comes after the
last slash in the path argument. The directory (or dir) name and base name of a path
are outlined . C:\Windows\System32\calc.exe Dir name Base name .
The base name follows the last slash in a path and is the same as the filename. The dir
name is everything before the last slash
,
os.path.split() to get a tuple value with these two strings, note that os.path.split() does not take
a file path and return a list of strings of each folder. For that, use the split() string method and
split on the string in os.sep.
The split() string method will work to return a list of each part of the path.
The os.path module provides functions for finding the size of a file in bytes and the files and
folders inside a given folder.
Calling os.path.getsize(path) will return the size in bytes of the file in the path argument.
>>> os.path.getsize('C:\\Windows\\System32\\calc.exe')
27648
• Calling os.listdir(path) will return a list of filename strings for each file in the path argument.
>>> os.listdir('C:\\Windows\\System32')
to find the total size of all the files in this director, use os.path.getsize() and os.listdir() together.
>>> totalSize = 0
//loop over each filename in the C:\Windows\System32 folder, the totalSize variable is
incremented by the size of each file.
//call os.path.getsize(),
//After looping through all the files, print totalSize to see the total size of the C:\Windows\
System32 folder.
2559970473
glob (short for global) is used to return all file paths that match a specific pattern.
The glob pattern '*.txt' will return files that start with any combination of characters as long as it ends
with the string '.txt', which is the text file extension.
>>> list(p.glob('project?.docx')
The glob expression 'project?.docx' will return 'project1.docx' or 'project5.docx', but it will not return
'project10.docx', because ? only matches to one character—so it will not match to the two-character
string '10'.
>>> list(p.glob('*.?x?')
The glob expression '*.?x?' will return files with any name and any three-character extension where the
middle character is an 'x'. combine the asterisk and question mark to create even more complex glob
expressions, l
the glob module is used similarly to find, locate, and search for all of the files that are
present in a system.
The glob module in Python does not require separate installations and comes with
every default Python installation.
Although glob is a module that comes with the default Python installation, it still requires
a separate import statement.
import glob
After the import, we have to refer to every function and method in this module with the
prefix glob.
import glob
files = glob.glob("./glob/home/sample_files/*") # Creating a glob object
print(files)
This snippet of code prints all the files within the sample_files folder located in the
home folder of the glob directory. The asterisk (*) stands for “multiple of any characters,
Asterisk (*): Matches zero or more characters
Regex and Glob patterns are similar ways of matching patterns in strings.
The main difference is that the regex pattern matches strings in code, while globbing matches file names
or file content in the terminal.
Globbing is the shell's way of providing regular expression patterns like other programming languages.
Another big difference is that regex has more options and features than glob patterns. It's more
advanced, and globbing has fewer options to get you through your search faster.
Path objects have methods to check whether a given path exists and whether it is a file or folder. a
variable p holds a Path object
Calling p.exists() returns True if the path exists or returns False if it doesn’t exist.
• Calling p.is_file() returns True if the path exists and is a file, or returns False otherwise.
• Calling p.is_dir() returns True if the path exists and is a directory, or returns False otherwise.
Plaintext files contain only basic text characters and do not include font, size, or color information.
Text files with the .txt extension or Python script files with the .py extension are examples of plaintext
files.
These can be opened with Windows’s Notepad or macOS’s TextEdit application.
programs can easily read the contents of plaintext files and treat them as an ordinary string value.
Binary files are all other file types, such as word processing documents, PDFs, images, spreadsheets, and
executable programs.
3. Close the file by calling the close() method on the File object.
The first one is the file name along with the complete path and
Type Hello, world! as the content of this text file and save it in your user home folder.
command will open the file in “reading plaintext” mode, or read mode for short.
When a file is opened in read mode, Python lets you only read data from the file;
Read mode is the default mode for files you open in Python. When a file is opened in read mode, Python
lets you only read data from the file;But if you don’t want to rely on Python’s defaults, you can explicitly
specify the mode by passing the string value 'r' as a second argument to open(). So
open('/Users/Al/hello .txt', 'r') and open('/Users/Al/hello.txt') do the same thing.
If you want to read the entire contents of a file as a string value, use the File object’s read() method.
Let’s continue with the hello.txt File object you stored in helloFile.
>>> helloContent
'Hello, world!'
think of the contents of a file as a single large string value, the read() method returns the string that is
stored in the file.
The readlines() method to get a list of string values from the file, one string for each line of text.
For example, create a file named sonnet29.txt in the same directory as hello.txt and write the following
text in it:
When, in disgrace with fortune and men's eyes, I all alone beweep my outcast state, And trouble deaf
heaven with my bootless cries, And look upon myself and curse my fate, Make sure to separate the four
lines with line breaks.
>>> sonnetFile.readlines()
[When, in disgrace with fortune and men's eyes,\n', ' I all alone beweep my outcast state,\n', And
trouble deaf heaven with my bootless cries,\n', And look upon myself and curse my fate,']
Note that, except for the last line of the file, each of the string values ends with a newline character \n.
A list of strings is often easier to work with than a single large string value.
Explain write() method
Writing to Files Python allows you to write content to a file in a way similar to how the print() function
“writes” strings to the screen.
To write into a file you’ve opened in read mode. you need to open it in “write plaintext” mode or
“append plaintext” mode, or write mode and append mode for short.
Write mode will overwrite the existing file and start from scratch.
Pass 'w' as the second argument to open() to open the file in write mode.
Append mode, on the other hand, will append text to the end of the existing file.
Pass 'a' as the second argument to open() to open the file in append mode.
If the filename passed to open() does not exist, both write and append mode will create a new, blank
file.
>>> baconFile.write('Hello, world!\n') // Calling write() on the opened file and passing write() the string
argument 'Hello, world! /n' writes the string to the file
. To add text to the existing contents of the file instead of replacing the string we just wrote,
>>> baconFile.write('Bacon is not a vegetable.') // We write 'Bacon is not a vegetable.' to the file
>>> baconFile = open('bacon.txt') // open the file in its default read mode, , close the file,
>>> content = baconFile.read() // call read(), store the resulting File object in content
Shelve Module, an effective tool for storing or persistent data storage. The shelve
module will let you add Save and Open features to your program.
The Shelve module is used to store data when using a relational database is not
recommended. A shelf object is a dictionary-like object, which is defined in this
module. Keys in shelf objects are strings and values are Python objects, that can be
handled by the Pickle module. The shelve module comes with Python’s standard utility
module, so there is no need to install it externally. The shelve module is used when
we need to store data that is small in size and less complex. For large and
complex data we use a database
The Shelf object has following methods available −
1
close()
synchronise and close persistent dict object.
2
sync()
Write back all entries in the cache if shelf was opened with writeback set to
True.
3
get()
returns value associated with key
4
items()
list of tuples – each tuple is key value pair
5
keys()
list of shelf keys
6
pop()
remove specified key and return the corresponding value.
7
update()
Update shelf from another dict/iterable
8
values()
list of shelf values
The shelve module frees you from worrying about how to store your program’s data to a file.
Your programs can use the shelve module to later reopen and retrieve the data from these shelf files.
Shelf values don’t have to be opened in read or write mode—they can do both once opened.
shelf values have keys() and values() methods that will return list-like values of the keys and values in
the shelf.
For example, if you ran a program and entered some configuration settings, you could save those
settings to a shelf file and then have the program load them the next time it is run. Enter the following
into the interactive shell:
>>> import shelve //To read and write data using the shelve module, you first import shelve.,
>>> cats = ['Zophie', 'Pooka', 'Simon'] // When We create a list cats and then store the returned shelf
value in a variable.
>>> shelfFile['cats'] = cats // write shelfFile['cats'] = cats to store the list in shelfFile as a value associated
with the key 'cats' (like in a dictionary). and You can make changes to the shelf value as if it were a
dictionary.
After running the previous code on Windows, you will see three new files in the current working
directory: mydata.bak, mydata.dat, and mydata.dir. >>> shelfFile = shelve.open('mydata') // we open
the shelf files to check that our data was stored correctly
>>> type(shelfFile)
>>> shelfFile['cats'] // Entering shelfFile['cats'] returns the same list that we stored earlier,
One unique feature of pprint output is that the dictionaries are automatically sorted before the
display representation is formatted.
The pprint module contains definition of PrettyPrinter class. Its constructor takes
following format −
Syntax:
pprint.PrettyPrinter(indent, width, depth, stream, compact)
The indent parameter defines indentation added on each recursive level. Default is 1.
The width parameter by default is 80. Desired output is restricted by this value. If the
length is greater than width, it is broken in multiple lines.
The depth parameter controls number of levels to be printed.
The stream parameter is by default std.out – the default output device. It can take any
stream object such as file.
The compact parameter id set to False by default. If true, only the data adjustable
within width will be displayed.
The PrettyPrinter class defines following methods −
pprint() − prints the formatted representation of PrettyPrinter object
pformat() − Returns the formatted representation of object, based on parameters to the
constructor.
# A python code without pprint
import requests
def geocode(address):
url = "https://maps.googleapis.com/maps/api/geocode/json"
resp = requests.get(url, params = {'address': address})
return resp.json()
def geocode(address):
url = "https://maps.googleapis.com/maps/api/geocode/json"
resp = requests.get(url, params = {'address': address})
return resp.json()