Skip to content

3 、字符串


一、repr()🧀

  • repr():返回对象的“官方字符串表示”,更精确,主要给程序看,方便调试。
  • print()(实际调用 str()):返回对象的“可读字符串表示”,更友好,主要给人看。

二、字符串常量🧀

import string
print(string.ascii_letters)   # abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
print(string.ascii_lowercase) # abcdefghijklmnopqrstuvwxyz
print("-----------")
print(string.ascii_uppercase) # ABCDEFGHIJKLMNOPQRSTUVWXYZ
print(string.digits)          # 0123456789
print("-----------")
print(string.punctuation)     # '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
print(string.printable)       # digits + letters + punctuation + whitespace
print("-----------")
print(string.whitespace)      # space + tab + linefeed + return + ...

三、字符串操作符🧀

1、+*🧀

print("abc" + "def") 
print("abc" * 3) 

2、in🧀

1
2
3
4
5
# 输出True/False
print("ring" in "strings")  # True
print("wow" in "amazing!")  # False
print("Yes" in "yes!")      # False
print("" in "No way!")      # True

3、索引和切片🧀

1
2
3
4
5
s = "abcdefgh"
print(s)
# 负向索引
print(s[-1])
print(s[-2])
s = "abcdefgh"
print(s)
# 切片
"""
切片是左闭右开区间
"""
print(s[0:3])
print(s[1:3])
"""
切片也可以有步长作为第三个参数
"""
print(s[1:7:2])
print(s[1:7:3])
1
2
3
4
5
6
7
# 反转字符串使用切片
def ReverseString(s):
    return s[::-1]

# 使用内置函数
def ReverseString2(s):
    return ''.join(reversed(s))

四、遍历🧀

Bug

字符串是不可变的

1
2
3
4
5
6
7
s = "abcde"

for i in range(0,len(s)):
    print(i,s[i])

for c in s:
    print(c)
  • 分隔输出
1
2
3
names = "Billy,Devlin,Tommy,Josh,Lucia,"
for name in names.split(","):
    print(name)
  • 分行输出
quotes = """\
Dijkstra: Simplicity is prerequisite for reliability.
Knuth: If you optimize everything, you will always be unhappy.
Dijkstra: Perfecting oneself is as much unlearning as it is learning.
Knuth: Beware of bugs in the above code; I have only proved it correct, not tried it.
Dijkstra: Computer science is no more about computers than astronomy is about telescopes.
"""
for line in quotes.splitlines():
    if line.startswith("Dijkstra"):
        print(line)

五、转义符🧀

转义字符 描述 示例代码 输出结果/说明
\\ 反斜杠 print("\\") \
\' 单引号 print('\'') '
\" 双引号 print("\"") "
\a 响铃(Alert) print("\a") 响一声(部分终端有效)
\b 退格(Backspace) print("AB\bC") AC(B 被删掉)
\n 换行(newline) print("Hello\nWorld") Hello``World
\t 横向制表符(Tab) print("A\tB") A B
\v 纵向制表符(Vertical Tab) print("A\vB") A       B
\f 换页符(Form Feed) print("A\fB") A       B
\r 回车(Carriage Return) print("Hello\rWorld") World(覆盖前部分)
\000 空字符(Null) print("\000") 显示为空
\ooo 八进制字符(ooo为0~7) print("\110\145\154\154\157") Hello
\xhh 十六进制字符(hh为两位十六进制数) print("\x48\x65\x6c\x6c\x6f") Hello

六、内建函数🧀

函数 用途
len() 返回长度
chr() 返回ASCII码代表的字母
ord() 返回ASCII码
eval() 把字符串当作表达式运行(⚠️安全隐患)

1、判断🧀

函数 用途
isalnum() 判断字符串是否只包含字母和数字(字母或数字
isalpha() 判断字符串是否只包含字母(不包含数字或其他符号)
isdigit() 判断字符串是否只包含数字(只能是 0-9)
islower() 判断字符串中的字母是否全为小写
isupper() 判断字符串中的字母是否全为大写
isspace() 判断字符串是否只包含空白字符(空格、换行、制表等)

2、编辑🧀

函数 用途
lower() 返回将字符串中所有字母转换为小写的新字符串
upper() 返回将字符串中所有字母转换为大写的新字符串
strip() 去除字符串两端的空白字符(空格、换行、制表符等)
replace(old, new) 将字符串中的指定子串 old 替换为 new,返回新字符串

3、子串搜索🧀

函数 用途说明
count("<target>") 统计子串 <target> 在字符串中出现的次数
startswith("<target>") 判断字符串是否以 <target> 开头,返回布尔值
endswith("<target>") 判断字符串是否以 <target> 结尾,返回布尔值
find("<target>") 返回 <target> 第一次出现的索引,找不到返回 -1
index("<target>") 返回 <target> 第一次出现的索引,找不到会报错

七、f-string🧀

在 f-string 中,表达式被花括号 {} 包围,Python 会在运行时将表达式的结果插入到字符串中。

  • 当然也可以使用 % 来格式化字符串(和C++基本一致)
1
2
3
4
x = 101
y = 1101

print(f"Do you know that {x}+{y}={x + y}")

八、基本文件 I/O🧀

def readfile(path):
    with open(path, 'r') as f:
        return f.read()

def writefile(file, content):
    with open(file, 'w') as f:
        f.write(content)

contentsToWrite = "This is a test."
writefile("test.txt", contentsToWrite)