7.1 字符串的定义(掌握)

字符串是一种由字符组成的不可变序列,用于表示文本数据。在 Python 中,字符串可以使用单引号 '、双引号 " 或三引号 '''/""" 来定义。

  • 单引号双引号:用于定义单行字符串,二者功能一致。

    name = 'aini'
    greeting = "Hello"
  • 三引号:用于定义多行字符串,适合长文本或多行注释。

    long_text = """这是一个
    多行字符串"""

7.2 字符串的基本操作(掌握)

7.2.1 字符串拼接

  • 使用 + 运算符将多个字符串拼接在一起。

    first_name = "aini"
    last_name = "Zhang"
    full_name = first_name + " " + last_name  # 输出 'aini Zhang'

7.2.2 字符串重复

  • 使用 * 运算符将字符串重复多次。

    repeated = "Hello" * 3  # 输出 'HelloHelloHello'

7.2.3 字符串长度

  • 使用 len() 函数获取字符串的字符数。

    message = "Hello, World!"
    print(len(message))  # 输出 13

7.2.4 字符串索引与切片

  • 索引:使用索引访问字符串中的单个字符,索引从 0 开始,支持负索引。

    text = "Python"
    print(text[0])   # 输出 'P'
    print(text[-1])  # 输出 'n'
  • 切片:使用切片获取字符串中的部分内容,格式为 字符串[起始:结束:步长]

    text = "Python"
    print(text[1:4])     # 输出 'yth'
    print(text[:3])      # 输出 'Pyt'
    print(text[::2])     # 输出 'Pto'
    print(text[::-1])    # 输出 'nohtyP'(字符串反转)

7.3 字符串的常用方法(掌握)

Python 提供了丰富的字符串方法,以下是常用的字符串方法,主要用于字符串的处理和格式化。

7.3.1 upper()lower():转换大小写

  • upper():将字符串全部转换为大写。
  • lower():将字符串全部转换为小写。

    text = "Hello World"
    print(text.upper())  # 输出 'HELLO WORLD'
    print(text.lower())  # 输出 'hello world'

7.3.2 strip():去除空白字符

  • strip():去除字符串两端的空白字符(包括空格、换行符等)。
  • lstrip():去除左侧空白字符。
  • rstrip():去除右侧空白字符。

    text = "   Hello World   "
    print(text.strip())   # 输出 'Hello World'
    print(text.lstrip())  # 输出 'Hello World   '
    print(text.rstrip())  # 输出 '   Hello World'

7.3.3 replace():替换子字符串

  • replace(old, new):将字符串中的 old 替换为 new

    text = "Hello World"
    print(text.replace("World", "Python"))  # 输出 'Hello Python'

7.3.4 split()join():拆分与合并字符串

  • split(separator):根据指定的分隔符将字符串拆分成列表。如果不指定分隔符,默认按空白字符拆分。

    text = "Hello World"
    print(text.split())         # 输出 ['Hello', 'World']
    print(text.split('o'))      # 输出 ['Hell', ' W', 'rld']
  • join(iterable):将可迭代对象中的元素连接成一个字符串,以调用者作为分隔符。

    words = ["Hello", "Python", "World"]
    print(" ".join(words))      # 输出 'Hello Python World'

7.3.5 find()index():查找子字符串

  • find(sub):查找子字符串 sub 的位置,找到则返回索引,否则返回 -1。
  • index(sub):与 find 类似,但如果找不到会引发 ValueError

    text = "Hello World"
    print(text.find("World"))   # 输出 6
    print(text.index("World"))  # 输出 6

7.4 字符串格式化(掌握)

Python 提供了多种格式化字符串的方法,便于拼接变量和字符串。

7.4.1 f-string 格式化(Python 3.6 及以上)

  • 使用 f"{变量}" 的方式嵌入变量,非常直观且易读。

    name = "aini"
    age = 23
    message = f"Hello, my name is {name} and I am {age} years old."
    print(message)  # 输出 'Hello, my name is aini and I am 23 years old.'

7.4.2 str.format() 方法

  • 使用 {} 占位符,并在字符串末尾调用 .format() 方法填充变量。

    name = "aini"
    age = 23
    message = "Hello, my name is {} and I am {} years old.".format(name, age)
    print(message)  # 输出 'Hello, my name is aini and I am 23 years old.'

7.4.3 百分号 % 格式化(旧方法)

  • 使用 % 运算符来进行格式化,在旧代码中仍然常见。

    name = "aini"
    age = 23
    message = "Hello, my name is %s and I am %d years old." % (name, age)
    print(message)  # 输出 'Hello, my name is aini and I am 23 years old.'

7.5 字符串的编码与解码(了解)

编码与解码用于将字符串转换为字节或将字节转换为字符串。通常用于处理文件、网络传输和多语言文本处理。

7.5.1 encode():编码字符串

  • encode(encoding):将字符串转换为指定编码格式的字节对象(bytes)。

    text = "Hello"
    byte_text = text.encode("utf-8")
    print(byte_text)  # 输出 b'Hello'

7.5.2 decode():解码字节

  • decode(encoding):将字节对象转换回指定编码格式的字符串。

    byte_text = b'Hello'
    text = byte_text.decode("utf-8")
    print(text)  # 输出 'Hello'

7.6 字符串的常见检查方法(掌握)

用于判断字符串是否符合特定格式或内容。

7.6.1 isalpha():检查是否全为字母

  • 返回 True 如果字符串只包含字母且非空,否则返回 False

    text = "Hello"
    print(text.isalpha())  # 输出 True

7.6.2 isdigit():检查是否全为数字

  • 返回 True 如果字符串只包含数字且非空,否则返回 False

    text = "12345"
    print(text.isdigit())  # 输出 True

7.6.3 isalnum():检查是否全为字母和数字

  • 返回 True 如果字符串只包含字母和数字且非空,否则返回 False

    text = "Hello123"
    print(text.isalnum())  # 输出 True

7.6.4 isspace():检查是否全为空白字符

  • 返回 True 如果字符串只包含空白字符(如空格、制表符)且非空,否则返回 False

    text = "   "
    print(text.isspace())  # 输出 True

结束

本文标题: Python3学习笔记第七篇--字符串

本文链接: https://blog.oyooy.com/archives/37.html

除非另有说明,本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议

声明:转载请注明文章来源。

最后修改:2025 年 02 月 02 日
如果觉得我的文章对你有用,请随意赞赏