Python Text Basics Flashcards
What are F String Literals ?
Format String Literals , are used to format strings in print method.
How to present dictionary value by using F String ?
d = {‘a’:123,’b’:456}
print(f”My No. is - {d[‘a’]}”)
How to present list value by using F String ?
mylist = [0,1,2,3]
print(f”My No. is - {mylist[0]}”)
How to create Tuple ?
myFruits = (‘Apple’,’Banana’,’Grapes’)
How to create List of Tuples ?
books = [(‘Author’,’Title’,’Pages’),(‘Twain’,’Rafting’,601),(‘Hamilton’,’Mythology’,144)]
*IMP
How to unpack tuples from List ?
books = [(‘Author’,’Title’,’Pages’),(‘Twain’,’Rafting’,601),(‘Hamilton’,’Mythology’,144)]+
for author,title,pages in books:
print(f”{author} {title} {pages}”)
How to fit numerical value with string in f string ?
profiles = [(‘Name’,’Age’),(‘Hemant Kumar ‘,40)]
for name,age in profiles:
print(f”{name:
How to set the padding between output of two variables with fstring ?
name = ‘Hemant Kumar’
age = 32
print(f”{name:{10}} {age:{5}}”)
*IMP
How to Print line with variable output using fstring ?
name = ‘Hemant Kumar’
age = 32
print(f”{name:-{5}}”)
How to Create a Data time Object?
from datetime import datetime
today = datetime(year=2019,month=2,day=28)
What is the website which gives reference to format time ?
The website is strtime.org
How to format date object with print method ?
from datetime import datetime
today = datetime(year=2019,month=2,day=28)
print(f”{today:%B %d,%Y}”)
B for Full Month
d for Day
Y for Full Year
How to create text file in Jupiter Notebook ?
%%writefile test.txt
Hello, this is test file,
This is second line
How to get current Absolute Path ?
using pwd
How to create a file object to read/write a file ?
We have to use open() method .
myfile = open(‘test.txt’)
File name in Python ,Windows, Linux, MacOS
We have to use double backslash in Windows, & forward slash in Linuc/MacOS
Windows :
‘C:\Users\cs1\MEGAsync\PythonCoding
Linux : /home/hemant/
How to read a text file ?
myfile.read()
What happens if we read text files by two times ?
myfile. read()
myfile. read()
I we read file first time , the curson goes to end of file , & we read file second time it shows nothing, because cursor is in the end of file .
How to move file cursor at index position zero or at beginning of file?
myfile.seek(0)
How to save content of file in variable ?
content = myfile.read()
print(content)
What are literals in python?
Literals are the constant values assigned to the constant variables
How to close a text file ?
myfile.close()
How to create a list of lines from text file ?
myfile = open('test.txt') mylines = myfile.readlines() for line in mylines: print(line) myfile.close()
How to split/fetch first word from lines
in text file ?
myfile = open('test.txt') mylines = myfile.readlines() for line in mylines: print(line.split()[0]) myfile.close()