0% found this document useful (0 votes)
11 views20 pages

Python Programming Lecture4

The document provides an overview of strings in Python, highlighting their immutability and various operations such as splitting, joining, and formatting. It also covers basic input/output operations, including reading from and writing to files, as well as handling exceptions. Additionally, it demonstrates how to manage file I/O using context managers for better resource management.

Uploaded by

ph25c013
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)
11 views20 pages

Python Programming Lecture4

The document provides an overview of strings in Python, highlighting their immutability and various operations such as splitting, joining, and formatting. It also covers basic input/output operations, including reading from and writing to files, as well as handling exceptions. Additionally, it demonstrates how to manage file I/O using context managers for better resource management.

Uploaded by

ph25c013
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

String

91
String
● A string in Python is a sequence of characters
● Strings are immutable

a = "Higgs boson"
b = 'aka, the God particle'
C = """ # span multiple lines
was discovered
at the Large Hadron Collider
10 years ago
"""

# quoted string
print("He asked,\"Which is your favorite team?\"")
print('He asked, "Which is your favorite team?"')
92
String
>>> import string # load the module in memory
>>> dir(string)
[... 'atof', 'atof_error', 'atoi',
'atoi_error', 'atol', 'atol_error',
'capitalize', 'capwords', 'center', 'count',
'digits', 'expandtabs', 'find', 'hexdigits',
'index', 'index_error', 'join', 'joinfields',
'letters', 'ljust', 'lower', 'lowercase',
'lstrip', 'maketrans', 'octdigits',
'printable', 'punctuation', 'replace',
'rfind', 'rindex', 'rjust', 'rsplit',
'rstrip', 'split', 'splitfields', 'strip',
'swapcase', 'translate', 'upper',
'uppercase', 'whitespace', 'zfill']
93
String object operations
>>> s = 'Hello World!' >>> [Link]('Hello')
True
>>> [Link]()
False >>> [Link](" ")
['Hello', 'World!']
>>> [Link]('W')
>>> [Link]()
6
'HELLO WORLD!'
>>> [Link]('W') >>> [Link]()
6 'hELLO wORLD!'
>>> [Link]('W') >>> [Link]('World','Globe')
False 'Hello Globe!'
>>> s = 'Hello\tWorld!'
>>> s
'Hello\tWorld!'
>>> [Link]()
'Hello World!' 94
String operations

Convert a string
'1,2,3,4,5,6,7,8'
to
'1:2:3:4:5:6:7:8'

95
String operations : split & join
>>> astr = '1,2,3,4,5,6,7,8'
>>> list = [Link](',')
>>> list
['1','2','3','4','5','6','7','8']

>>> ':'.join(list)
'1:2:3:4:5:6:7:8'

# all in one line


>>> ':'.join('1,2,3,4,5,6,7,8'.split(','))
'1:2:3:4:5:6:7:8'
96
String Formatting [C style]

>>> print("Today's price: %f" % 50.4625)


Today's price: 50.462500

>>> print("Today's price: %.2f" % 50.4625)


Today's price: 50.46

>>> print("Change since yesterday: %+.2f"


% 1.5)
Change since yesterday: +1.50

97
String Formatting [Modern]
>>> print("{:.3f}".format([Link]))
3.142
>>> print("{0:d} – {0:x} – {0:o} – {0:b}".format(21))
21 - 15 - 25 - 10101
>>> s = "I prefer {0} over {1}".format('emacs', 'vi')
>>> s = "Lang: {lang}".format(lang="Python")
# defining format
>>> email_f = "Your email was {email}".format
>>> print(email_f(email="bob@[Link]"))

98
Basic Input/Output

99
Basic I/O
>>> import sys
>>> dir(sys) # returns a list
[... '__stderr__', '__stdin__',
'__stdout__', 'maxsize',
'setrecursionlimit', 'settrace', 'stderr',
'stdin', 'stdout', 'subversion',
'version', 'version_info', 'warnoptions']
>>> type([Link])
<class '_io.TextIOWrapper'>
>>> type([Link])
<class '_io.TextIOWrapper'>
>>> type([Link])
<class '_io.TextIOWrapper'> 100
Basic I/O
● Redirect stdout to a file

>>> import sys


>>> f = open('[Link]', 'w')
>>> [Link] = f
>>> print('hello world!')
>>> [Link]()
>>> [Link] = sys.__stdout__
>>> print('hello world!')
hello world!
101
Basic I/O
>>> data = [Link]()
hello
world!
how
do
you do?

# CTRL-D
>>> print "Counted",len(data),"lines."
Counted 6 lines.
>>> print [Link]().upper()
Hello World! # press CTRL-D
HELLO WORLD! 102
built-in function input

>>> str = input("Enter your input: ")


Enter your input: [x*5 for x in
range(2,10,2)]

>>> print("evaluated input:", eval(str))


Received input is: [10, 20, 30, 40]

103
File I/O
player,country,testrun,odirun
Gavaskar,India,10122,3092
Border,Aus,11174,6524
Waugh,Aus,10927,7569
Lara,WI,11953,10405
Chanderpaul,WI,11219,8778
Jayawardene,SL,11319,11549
Tendulkar,India,15921,18426
Ponting,Aus,13378,13704
Kallis,SA,13289,11574
Dravid,India,13288,10889
Sangakkara,SL,11151,12548
104
File I/O
f = open('[Link]', 'r') # r -> read
#lines = [Link]()
#[Link]()
for line in f:
line = [Link]()
fields = [Link](",")
if fields[1] == 'India':
print(line)
[Link]()

105
File I/O
f = open('[Link]', 'r') # r -> read
for line in f:
line = [Link]()
fields = [Link](",")
if fields[1] == 'India':
print(line)
[Link]()

● what happens if
○ the file does not exist?
○ there is a comment line?
○ some lines are empty?
○ some rows do not have all the required fields?
106
File I/O – better approach
with open('[Link]', 'r') as f:
for line in f:
line = [Link]()
if [Link](‘#’): continue
fields = [Link](",")
if fields[1] == 'India':
print(line)

# file will be automatically closed

107
Exceptions in Python
[Link]

108
File I/O
#!/usr/bin/env python3
try:
f = open('[Link]', 'r')
for line in f:
line = [Link]()
#list = [Link](",")
#if len(list) < 3: continue
try:
n1,n2,n3 = [Link](",")
except ValueError:
continue
if n3 > n1:
print line
except IOError:
raise
finally:
[Link]() 109
File Output
# Open a file
fo = open("[Link]", "w")
[Link]("Python is great!!\n")

# Close opened file


[Link]()

110

You might also like