Skip to content

字符串

  • 字符串是 Python 中最常用的数据类型。

定义

  • 字符串的定义使用引号 '' 或者 "" 包裹。
  • 字符串是不可变数据类型。
python
a = "hello"
print(a)

基本操作

python
str = "hello world"
print (str)           # 输出完整字符串
print (str[0])        # 输出字符串中的第一个字符
print (str[2:5])      # 输出字符串中第三个至第六个之间的字符串
print (str[2:])       # 输出从第三个字符开始的字符串
print (str * 2)       # 输出字符串两次
print (str + "TEST")  # 输出连接的字符串

字符串格式化

python
money = 50
ice_cream = 10
cole = 5
print("我有{}元".format(money))
print("冰淇淋单价{}元".format(ice_cream))
print("可乐单价%s元" % (cole))
# 方式1
print("我买了1冰淇淋和2可乐,还剩{}元".format(money - ice_cream * 1 - cole * 2))
# 方式2
print("我买了1冰淇淋和2可乐,还剩{0}元".format(money - ice_cream * 1 - cole * 2))
# 方式3
print("我买了1冰淇淋和2可乐,还剩{money}元".format(money = money - ice_cream * 1 - cole * 2))
# 方式4 推荐方式
print(f"我买了1冰淇淋和2可乐,还剩{money}元")
# 方式5
print("我买了1冰淇淋和2可乐,还剩%s元" % (money - ice_cream * 1 - cole * 2))

frub

  • f 字符串格式化
  • r 原始字符串
  • u Unicode 字符串
  • b 字节字符串
python
# 字符串格式化
name = "world"
str1 = f"hello {name}"
print(str1) # hello world

# 原始字符串
str1 = r"hello\nworld"
print(str1) # hello\nworld

# Unicode字符串
str3 = u"hello world"
print(str3) # u'hello world' 变成成字节
str4 = str3.decode("utf-8") # 解码成字符串
str4.encode("utf-8") # 编码成字节

# 字节字符串
str2 = b"hello world"
print(str2) # b'hello world'

三引号

可以将复杂的字符串进行赋值,使用''' 或者 """ 包裹。

常使用展示包含 代码块 防止代码块执行

python
str2 = """
字符串 <script></script>
"""
print(str2)

常用系统函数

python
a = "hello world"
# 把字符串的第一个字符大写
print(a.capitalize()) # Hello world

# 转换字符串中所有大写字符为小写
print(a.lower()) # hello world

# 转换字符串中的小写字母为大写
print(a.upper()) # HELLO WORLD

# 统计字符串中某个字符出现的次数
print(a.count("l")) # 3

# 检测 str 是否包含在 string 中,如果是返回开始的索引值,否则返回-1
print(a.find("l")) # 2

# 替换字符串中的某个字符
print(a.replace("l", "L")) # heLLo worLd

# 以 str 为分隔符截取字符串
print(a.split("l")) # ['he', '', 'o wor', 'd']

# 去掉字符串左右空格
print(a.strip()) # hello world

# 以 string 作为分隔符,将 seq 中所有的元素(的字符串表示)合并为一个新的字符串
print(" ".join(a.split("l"))) # he o wor d