Python基础 _string汇总

1. 字符串的定义与创建

  • 单引号双引号三引号都可以用于定义字符串。

    s1 = 'Hello'
    s2 = "Hello"
    s3 = '''Hello'''
    s4 = """Hello"""
    
  • 空字符串

    empty_str = ""
    
  • 字符串是不可变的,创建后不能修改字符。

    s = "hello"
    # s[0] = "H"  # 会抛出 TypeError
    

2. 转义字符

转义字符含义
\'单引号
\"双引号
\\反斜杠
\n换行符
\t制表符
\r回车符

示例:

s = "Hello\nWorld"
print(s)

3. 原始字符串

  • 使用 r 或 R 定义原始字符串,忽略反斜杠的转义功能:

    raw_str = r"C:\new_folder\test"
    

4. 字符串的常用操作

4.1 拼接与重复

  • 拼接:使用 +

    s1 = "Hello"
    s2 = "World"
    s3 = s1 + " " + s2  # 'Hello World'
    
  • 重复:使用 *

    s4 = "Hello" * 3  # 'HelloHelloHello'
    

4.2 获取长度

  • 使用

    len()
    

    函数:

    s = "Hello"
    print(len(s))  # 5
    

4.3 索引与切片

  • 索引:访问单个字符。

    s = "Python"
    print(s[0])  # 'P'
    print(s[-1])  # 'n'
    
  • 切片:提取子字符串。

    s = "Python"
    print(s[0:3])  # 'Pyt'
    print(s[::2])  # 'Pto'
    

4.4 字符串遍历

  • 使用 for 循环遍历字符串:

    for char in "Python":
        print(char)
    

5. 常用字符串方法

5.1 大小写转换

  • str.upper():转换为大写。
  • str.lower():转换为小写。
  • str.capitalize():首字母大写。
  • str.title():每个单词首字母大写。
  • str.swapcase():大小写互换。

5.2 查找与替换

  • str.find(sub):返回子串 sub 的索引,找不到返回 -1
  • str.replace(old, new):替换子串。
  • str.count(sub):统计子串出现的次数。

5.3 去除空白字符

  • str.strip():去除两侧空白字符。
  • str.lstrip():去除左侧空白字符。
  • str.rstrip():去除右侧空白字符。

5.4 内容判断

  • str.isalpha():是否全是字母。
  • str.isdigit():是否全是数字。
  • str.isalnum():是否全是字母和数字。
  • str.isspace():是否全是空白字符。

5.5 分割与连接

  • str.split(sep):按 sep 分割为列表。
  • str.join(iterable):将序列的元素连接为字符串。

5.6 对齐操作

  • str.center(width):居中对齐。
  • str.ljust(width):左对齐。
  • str.rjust(width):右对齐。

6. 字符串格式化

6.1 % 运算符

name = "Alice"
age = 30
s = "My name is %s and I am %d years old." % (name, age)

6.2 str.format()

name = "Bob"
age = 25
s = "My name is {} and I am {} years old.".format(name, age)

6.3 f-strings

name = "Alice"
age = 30
s = f"My name is {name} and I am {age} years old."

7. 字符串的编码与解码

7.1 编码

  • str.encode(encoding):将字符串编码为字节对象。

    s = "你好"
    b = s.encode('utf-8')  # 编码为 utf-8 字节
    

7.2 解码

  • bytes.decode(encoding):将字节对象解码为字符串。

    decoded_str = b.decode('utf-8')
    

8. 字符串比较

  • 使用比较运算符:==, !=, <, >, 按字典顺序进行比较。
s1 = "abc"
s2 = "abd"
print(s1 < s2)  # True

9. 字符串与其他类型转换

  • str():将其他类型转换为字符串。

    num = 123
    s = str(num)  # '123'
    
  • int()float():将字符串转换为数字。

    s = "456"
    num = int(s)  # 456
    

10. 多行字符串

  • 使用三引号定义多行字符串:

    s = """This is a multi-line
    string."""
    

11. 模板字符串

  • 使用 string.Template 实现简单的变量替换:

    from string import Template
    t = Template("My name is $name")
    s = t.substitute(name="David")
    

12. 正则表达式与字符串

  • re 模块支持正则表达式操作。

    import re
    pattern = r'\d+'
    s = "There are 123 apples"
    match = re.findall(pattern, s)  # ['123']
    
  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值