教程
任务
字符串
学习时间
5/22
笔记
字符串文字
# usually the same
print('missing')
print("missing")
# uncommon, but used as doc-strings
print('''missing''')
print("""missing""")
# use two types of quotation marks for this
print("聪明办法学 Python 第二版的课程简称是 'P2S'")
字符串中的换行符号
前面有反斜杠 \
的字符,叫做转义序列,例如\n
可以在字符串后面使用 反斜杠 \
来排除后面的换行
repr() vs print()
s1 = "Data\tWhale"
s2 = "Data Whale"
# print() can't differentiate their output
# but repr() can output the original content
print(repr(s1)) # 'Data\tWhale'
print(repr(s2)) # 'Data Whale'
python本身是没有多行注释的,三个引号包裹的字符串是表达式,python会运行并马上扔掉它
一些常量字符串
import string
print(string.printable)
print(repr(string.whitespace))
一些字符串的运算
in 运算
print("ring" in "strings") # True
字符串索引和切片
s = 'Datawhale'
print(s[len(s)-1]) # e
print(s[-1]) # e
s[start :end :step ]
s[::] == s[0:len(s):1]
# an elegant way to get reversed string
def reverseString(s):
return s[::-1]
print(reverseString(s))
s[0]='a' # error
s = 'a' + s[1:] # OK
字符串的循环
for c in s:
print(c)
# zip(a, b) gets one element from a and one from b at one time
for a, b in zip(s, reverseString(s)):
print(a, b)
# use split()
class_name = "learn python the smart way 2nd edition"
for word in class_name.split():
print(word)
"""
learn
python
the
smart
way
2nd
edition
"""
# use splitlines()
class_info = """\
聪明办法学 Python 第二版是 Datawhale 基于第一版教程的一次大幅更新。我们尝试在教程中融入更多计算机科学与人工智能相关的内容,制作“面向人工智能的 Python 专项教程”。
我们的课程简称为 P2S,有两个含义:
Learn Python The Smart Way V2,“聪明办法学 Python 第二版”的缩写。
Prepare To Be Smart, 我们希望同学们学习这个教程后能学习到聪明的办法,从容的迈入人工智能的后续学习。
"""
for line in class_info.splitlines():
if (line.startswith("Prepare To Be Smart")):
print(line)
# Prepare To Be Smart, 我们希望同学们学习这个教程后能学习到聪明的办法,从容的迈入人工智能的后续学习。
回文数Palindrome
def isPalindrome1(s):
return (s == reverseString(s))
def isPalindrome4(s):
while (len(s) > 1):
if (s[0] != s[-1]):
return False
s = s[1:-1]
return True
一些跟字符串相关的内置函数
str()
andlen()
print(str(len(string)))
chr()
andord()
chr(ord("A") + ord(" ")) == 'a'
s = "(3**2 + 4**2)**0.5"
print(eval(s)) # 5.0
# but eval() will execute the expression without safety measures
# not recommended
# 推荐使用 ast.literal_eval()
import ast
s_safe = "['p', 2, 's']"
s_safe_result = ast.literal_eval(s_safe)
print(s_safe_result)
print(type(s_safe_result))
一些字符串方法
# some are string type, others are bool type
s.isalnum()
s.isalpha()
s.isdigit()
s.islower()
s.isspace()
s.isupper()
s.lower()
s.upper()
"""
C语言中用c^32转换字符大小写是基于ASCII码的小技巧,不适合Unicode
而在Python中,使用.lower()和.upper()方法转换大小写,能正确处理包括Unicode在内的各种字符集的大小写转换规则,更加通用和可靠
"""
s.strip() # delete spaces in the beginning or at the end
s.replace(s1, s2)
s.count(s1)
s.startswith(s1)
s.endswith(s2)
s.find(s1) # return -1 if not found
s.index(s1) # report and error if not found
用 f-string
格式化字符串
x = "ice"
y = "cream"
z = "I scream"
print(f'你知道{x}+{y}是{x+y},但你知道{x}+{y}=>{z}吗')
其他格式化字符串的方法
%
方法format()
方法
基础文件操作
//和C的文件操作有点像
Open()
函数
open(filepath, readmode)
readmode: r, rb, w, a(追加写入)
文件对象
close( )
: 关闭文件- 在
r
与rb
模式下:read()
: 读取整个文件readline()
: 读取文件的一行readlines()
: 读取文件的所有行
- 在
w与
a`模式下:write()
:writelines()
:
read()
之后还要读取,则应该close()
后再打开
//C的rewind()
file = open('test.txt', 'w')
print(type(file)) # <class '_io.TextIOWrapper'>
file.write("this is for test")
file.close()
file = open('test.txt', 'r')
s = file.read() # output is abnormal if the "()" is missing
print(type(file))
print(s)
file.close() # seems OK if the "()" is missing
with
语句
文件操作推荐使用 with open("xxx") as yyy
,这样就不用写 f.close()
啦。
课后思考
Python format格式化函数 - 菜鸟教程
what else can python do for me?
how can I build a python project?