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

P6-String

The document covers various aspects of Python programming, focusing on strings, lists, and error handling. It explains character encoding standards, string immutability, methods for string manipulation, and the hierarchy of exceptions in Python. Additionally, it discusses the differences between strings and lists, and how to handle runtime errors using try and except blocks.

Uploaded by

s112701018.mg12
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)
12 views20 pages

P6-String

The document covers various aspects of Python programming, focusing on strings, lists, and error handling. It explains character encoding standards, string immutability, methods for string manipulation, and the hierarchy of exceptions in Python. Additionally, it discusses the differences between strings and lists, and how to handle runtime errors using try and except blocks.

Uploaded by

s112701018.mg12
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/ 20

PE2 Module 2

 Strings, String and List Methods, Exceptions,


 Characters, strings and coding standards;

 Strings vs. lists – similarities and differences;

 Lists methods;

 String methods;

 Python's way of handling runtime errors;

 Controlling the flow of errors using try and except;

 The hierarchy of exceptions.

廖文宏 Python Programming 1


2.1.1 Characters and Coding Standards
 Computers store characters as numbers. Every character
used by a computer corresponds to a unique number.
 e.g. ASCII (American Standard Code for Information
Interchange)

廖文宏 Python Programming 2


2.1.1.2 Internationalization
 how to encode other character than Latin alphabet
 a.k.a. internationalization (I18N)

 One of the solutions: extend ASCII code


 The first 128 are used for the standard Latin alphabet

(both upper-case and lower-case characters).


All the other national characters around the world are
used the remaining 128 locations.

廖文宏 Python Programming 3


2.1.1.2 Code Points and Code Pages
 Code Point
 a number which makes a character.

 For example, 32 is a code point which makes a SPACE in


ASCII encoding.
 Code Page
 a standard for using the upper 128 code points to store
specific national characters.
 For example, there are different code pages for Western
Europe and Eastern Europe, Cyrillic and Greek alphabets,
Arabic and Hebrew languages, and so on.
 This means that the same code point can make different
characters when used in different code pages.
 e.g. the code point 200 makes Č (a letter used by some Slavic
languages) when utilized by the ISO/IEC 8859-2 code page, and makes
Ш (a Cyrillic letter) when used by the ISO/IEC 8859-5 code page.

廖文宏 Python Programming 4


2.1.1.3 Unicode
 UCS-4
 32 bits, Unicode Standard

 The first 128 Unicode code points are identical to ASCII

 The first 256 Unicode code points are identical to the

ISO/IEC 8859-1 code page


 UTF-8 (Unicode Transformation Format)
 all Latin characters (and all standard ASCII characters)

occupy eight bits;


 non-Latin characters occupy 16 bits;

 CJK (China-Japan-Korea) ideographs occupy 24 bits.

 UTF-16, UTF-32
廖文宏 Python Programming 5
2.2.1 String
 Python's strings are immutable sequences.
 multiple line string, e.g.
'''
line 1
line 2
'''
 String Operators
 concatenate(join) +, +=

 replicate *, *=

 in, not in

廖文宏 Python Programming 6


2.2.1.4 find code-point value
 ord(char)
 return character's ASCII/Unicode code point

 e.g. ord('a') # 0x61, 97

 chr(code)
 takes a code point and returns its character

 e.g. chr(97) # 'a'

廖文宏 Python Programming 7


2.2.1.6 String Indexing
 Strings can be indexed (subscripted), with the first character
having index 0, e.g.
>>> word = 'Python'
>>> word[0] # character in position 0
'P'
>>> word[5] # character in position 5
'n'
>>> word[2:5] # characters from position 2 (included) to 5 (excluded)
'tho'
 Indices may also be negative numbers, to start counting
from the right

廖文宏 Python Programming 8


2.2.1.7 String Slicing
 One way to remember how slices work is to think of the
indices as pointing between characters

 index step
 e.g. word[0:6:2] # 'Pto'

 e.g. word[::-1] # 'nohtyP'

廖文宏 Python Programming 9


2.2.1.8 in, not in
 checks if a sub-string can be found anywhere within the
source string.
 e.g.
sentence = "This is a book."
print("book" in sentence) # True
print("are" not in sentence) # True

廖文宏 Python Programming 10


2.2.1.9 string is not a list
 you can delete list item by del, e.g. delete second item of
list by del list[2],
 but you cannot delete substring, e.g.
del string[2]
delete second char of string is illegal.
 because string is immutable
 s.append(), s.insert() is illegal too.

廖文宏 Python Programming 11


2.2.1.11 string operation
 len(string) : string length
 str() : convert number to string - 2.4.1.4
 list() : convert to list
 min() : finds the minimum element of the sequence -
2.2.1.11
 max() : finds the maximum element of the sequence -
2.2.1.12

廖文宏 Python Programming 12


2.3 String Methods
 string.index(substring) - 2.2.1.13
 find the first occurrence of substring in source string.

 string.count(substring) - 2.2.1.14
 string.capitalize(), .upper(), .lower(), .swapcase()
 string.center()
 string.endswith(substring), string.startswith(substring)
 string.find(substring)
 find the first occurrence of substring in source string.

 return -1 if not found

 2.3.1.17 一覽表
 https://docs.python.org/3/library/stdtypes.html#str
廖文宏 Python Programming 13
2.4 String Comparison
 just compares code point values, character by character
 relation between strings is determined by the first different
character
 longer string is considered greater, e.g.
'alpha' < 'alphabet'
 upper-case letters are taken as lesser than lower-case, e.g.
'Beta' < 'beta'
 '10' < '8' # because '1' < '8'
 Do not comparing strings against numbers, e.g.
'10' == 10 # False
'10' > 10 # TypeError Exception
廖文宏 Python Programming 14
2.4.1.3 Sort List containing Strings
 sorted()
 takes one argument (a list) and returns a new list

 list.sort()
 Sorting is performed in situ (affects the list itself), no

new list is created.

廖文宏 Python Programming 15


2.6 Error Handling
 Each time your code tries to do something
wrong/foolish/irresponsible/crazy/unenforceable, Python
does two things:
 it stops your program;

 it creates a special kind of data, called an exception.

 Both of these activities are called raising an exception.

廖文宏 Python Programming 16


2.6 try-except
 e.g.

廖文宏 Python Programming 17


2.7 Built-in Exceptions Hierarchy

廖文宏 Python Programming 18


2.7.1.5 Raise Exception
 e.g.
def bad_fun(n):
try:
return n / 0
except:
print("I did it again!")
raise
try:
bad_fun(0)
except ArithmeticError:
print("I see!")
print("THE END.")
廖文宏 Python Programming 19
2.7.1.7 Assertion
 e.g.
import math
x = float(input("Enter a number: "))
assert x >= 0.0
x = math.sqrt(x)
print(x)
 It evaluates the expression;
 if the expression evaluates to True, it won't do anything
 otherwise, it automatically and immediately raises an
exception AssertionError

廖文宏 Python Programming 20

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