notes for p2s chapter 6

HydroOJ个人主页

教程

slides/chapter 6

任务

字符串

学习时间

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() and len()
print(str(len(string)))
  • chr() and ord()
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( ): 关闭文件
  • rrb模式下:
    • 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?

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值