字符串

对应教学日历:讲次 5


一、字符串基础

定义

包含在单引号、双引号、三引号之间的字符集合。

s1 = 'hello'
s2 = "world"
s3 = '''多行
字符串'''

索引

fstr = "I love ECUST"
fstr[0]     # 'I'
fstr[-4]    # 'C'
fstr[7:]    # 'ECUST'
fstr[::-1]  # 'TSUCE evol I'(逆序)
  • 第一个字符索引为 0,最后一个为 -1
  • 切片 [i:j] 从下标i到下标j-1
  • 切片 [i:j:k] 中k为步长(可为负数)

常见索引操作

# 从右向左取第2个字符
s[-2]        # 正确
# s[2]       # 从左取第3个字符
# s[:-2]     # 从头到倒数第2个之前

二、字符串运算

运算符含义示例结果
+连接"Study" + " " + "hard"'Study hard'
*复制"hard" * 3'hardhardhard'
in包含判断"hard" in resultTrue
not in不包含判断"cat" not in resultTrue
fstr = "我在山海里,爱在河流里,你在云雾里。"
result = fstr[0] + fstr[6] + fstr[-6]
result * 3          # '我爱你我爱你我爱你'
"爱" in result      # True

三、常用字符串方法

方法功能示例
upper()转大写"hello".upper()"HELLO"
lower()转小写"HELLO".lower()"hello"
strip()去两端空格" hi ".strip()"hi"
split()分割为列表"a b c".split()['a','b','c']
replace(a,b)替换"dog".replace("dog","cat")"cat"
isdigit()是否全数字"123".isdigit()True
isalpha()是否全字母"abc".isalpha()True
count(x)统计次数"hello".count("l")2
fstr = "It is a dog. \n"
fstr.upper()        # 'IT IS A DOG. \n'
fstr.lower()        # 'it is a dog. \n'
fstr.strip()        # 'It is a dog.'
fstr.split()        # ['It', 'is', 'a', 'dog.']
fstr.replace("dog", "cat")  # 'It is a cat. \n'

四、转义字符

转义字符描述转义字符描述
\n换行\t横向制表位
\\反斜杠符\r回车
\'单引号\b退格键
\"双引号\a响铃
\(行尾)续行符\ooo八进制数

五、字符串常量(string模块)

import string
string.punctuation     # '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
string.digits          # '0123456789'
string.ascii_letters   # 所有字母

作业示例

恺撒密码

plain = input("请输入明文: ")
for p in plain:
    if "a" <= p <= "z":
        print(chr(ord("a") + (ord(p) - ord("a") + 3) % 26), end='')
    elif "A" <= p <= "Z":
        print(chr(ord("A") + (ord(p) - ord("A") + 3) % 26), end='')
    else:
        print(p, end="")

要点

  • ord() 获取字符ASCII码
  • chr() 将ASCII码转回字符
  • % 26 实现字母循环(z后面是a)

手机号码加密(批量+文件)

while True:
    tele = input("请输入手机号码:")
    if tele == "0":
        print("程序运行结束!")
        break
    new = tele[0:3] + "*" * 4 + tele[7:]
    print("加密后手机号码:%s" % new)

英文文本分析

import string
sen = input("请输入一段英文:")
sen = sen.lower()
for i in string.punctuation:
    if i in sen:
        sen = sen.replace(i, " ")
result = sen.split()
counts = {}
for i in result:
    counts[i] = counts.get(i, 0) + 1

要点

  • string.punctuation 包含所有标点符号
  • 先转小写,再替换标点为空格,再分割为单词列表

作业重点

  • 字符串是不可变序列类型
  • 索引从0开始,负数索引从-1开始
  • 切片 [i:j] 不包括下标j
  • [::-1] 实现字符串逆序
  • innot in 判断子串是否存在
  • split() 默认按空格分割,返回列表
  • replace(old, new) 替换所有匹配项
  • ord()chr() 在ASCII码和字符之间转换