Python字符串所有方法及用法汇总

Python 的字符串(str)类型提供了许多方法,用于操作和处理字符串数据。以下是一些常用的字符串方法及其示例:

方法示例:

  1. str.lower():将字符串中的所有字符转换为小写。

     
      
    s = "Hello, World!"
    print(s.lower()) # 输出: hello, world!
  2. str.upper():将字符串中的所有字符转换为大写。

     

    python复制代码

    s = "Hello, World!"
    print(s.upper()) # 输出: HELLO, WORLD!
  3. str.capitalize():将字符串的第一个字符转换为大写,其余字符转换为小写。

     

    python复制代码

    s = "hello, world!"
    print(s.capitalize()) # 输出: Hello, world!
  4. str.title():将字符串中的每个单词的首字母转换为大写,其余字符转换为小写。

     

    python复制代码

    s = "hello, world!"
    print(s.title()) # 输出: Hello, World!
  5. str.swapcase():将字符串中的大写字符转换为小写,小写字符转换为大写。

     

    python复制代码

    s = "Hello, World!"
    print(s.swapcase()) # 输出: hELLO, wORLD!
  6. str.strip([chars]):移除字符串开头和结尾的空白字符(默认为空格、换行符等),也可以指定要移除的字符。

     

    python复制代码

    s = " Hello, World! "
    print(s.strip()) # 输出: Hello, World!
    s = "xxxHello, World!xxx"
    print(s.strip('x')) # 输出: Hello, World!
  7. str.lstrip([chars]):移除字符串开头的空白字符(或指定字符)。

     

    python复制代码

    s = " Hello, World! "
    print(s.lstrip()) # 输出: Hello, World!
    s = "xxxHello, World!xxx"
    print(s.lstrip('x')) # 输出: Hello, World!xxx
  8. str.rstrip([chars]):移除字符串结尾的空白字符(或指定字符)。

     

    python复制代码

    s = " Hello, World! "
    print(s.rstrip()) # 输出: Hello, World!
    s = "xxxHello, World!xxx"
    print(s.rstrip('x')) # 输出: xxxHello, World!
  9. str.split([sep, maxsplit]):将字符串分割成一个列表,默认按空白字符分割,也可以指定分隔符和最大分割次数。

     

    python复制代码

    s = "Hello, World, Python!"
    print(s.split()) # 输出: ['Hello,', 'World,', 'Python!']
    print(s.split(', ')) # 输出: ['Hello', 'World', 'Python!']
    print(s.split(',', 1)) # 输出: ['Hello', ' World, Python!']
  10. str.rsplit([sep, maxsplit]):类似于 split(),但分割是从字符串的末尾开始的。

     

    python复制代码

    s = "Hello, World, Python!"
    print(s.rsplit()) # 输出: ['Hello,', 'World,', 'Python!']
    print(s.rsplit(', ', 1)) # 输出: ['Hello, World', 'Python!']
  11. str.join(iterable):将可迭代对象(如列表、元组)中的字符串元素连接成一个新的字符串,元素之间用原字符串作为分隔符。

     

    python复制代码

    lst = ['Hello', 'World', 'Python']
    print(', '.join(lst)) # 输出: Hello, World, Python
  12. str.find(sub[, start[, end]]):返回子字符串 sub 在原字符串中最低索引(从左到右),如果未找到则返回 -1。可以指定搜索的起始和结束位置。

     

    python复制代码

    s = "Hello, World!"
    print(s.find('World')) # 输出: 7
    print(s.find('Python')) # 输出: -1
  13. str.rfind(sub[, start[, end]]):类似于 find(),但搜索是从右到左的。

     

    python复制代码

    s = "Hello, Hello, World!"
    print(s.rfind('Hello')) # 输出: 13
  14. str.index(sub[, start[, end]]):类似于 find(),但如果未找到子字符串则引发 ValueError 异常。

     

    python复制代码

    s = "Hello, World!"
    print(s.index('World')) # 输出: 7
    # print(s.index('Python')) # 会引发 ValueError
  15. str.rindex(sub[, start[, end]]):类似于 index(),但搜索是从右到左的。

     

    python复制代码

    s = "Hello, Hello, World!"
    print(s.rindex('Hello')) # 输出: 13
  16. str.count(sub[, start[, end]]):返回子字符串 sub 在原字符串中出现的次数,可以指定搜索的起始和结束位置。

     

    python复制代码

    s = "Hello, Hello, World!"
    print(s.count('Hello')) # 输出: 2
  17. str.replace(old, new[, count]):将字符串中的 old 子字符串替换为 new,可以指定替换的次数。

     

    python复制代码

    s = "Hello, Hello, World!"
    print(s.replace('Hello', 'Hi')) # 输出: Hi, Hi, World!
    print(s.replace('Hello', 'Hi', 1)) # 输出: Hi, Hello, World!
  18. str.startswith(prefix[, start[, end]]):检查字符串是否以指定的前缀开始,可以指定检查的起始和结束位置。

     

    python复制代码

    s = "Hello, World!"
    print(s.startswith('Hello')) # 输出: True
    print(s.startswith('World')) # 输出: False
  19. str.endswith(suffix[, start[, end]]):检查字符串是否以指定的后缀结束,可以指定检查的起始和结束位置。

     

    python复制代码

    s = "Hello, World!"
    print(s.endswith('World!')) # 输出: True
    print(s.endswith('Hello')) # 输出: False
  20. str.isalnum():如果字符串中的所有字符都是字母或数字且至少有一个字符,则返回 True,否则返回 False。

     

    python复制代码

    s = "Hello123"
    print(s.isalnum()) # 输出: True
  21. str.isalpha():如果字符串中的所有字符都是字母且至少有一个字符,则返回 True,否则返回 False。

     

    python复制代码

    s = "Hello"
    print(s.isalpha()) # 输出: True
  22. str.isdigit():如果字符串中的所有字符都是数字且至少有一个字符,则返回 True,否则返回 False。

     

    python复制代码

    s = "123"
    print(s.isdigit()) # 输出: True
  23. str.isspace():如果字符串中的所有字符都是空白字符且至少有一个字符,则返回 True,否则返回 False。

     

    python复制代码

    s = " "
    print(s.isspace()) # 输出: True
  24. str.istitle():如果字符串是标题化的(即每个单词的首字母大写,其余字符小写),则返回 True,否则返回 False。

     

    python复制代码

    s = "Hello World"
    print(s.istitle()) # 输出: True
  25. str.zfill(width):用零填充字符串的左侧,使其总长度达到指定的宽度。

     

    python复制代码

    s = "42"
    print(s.zfill(5)) # 输出: 00042
  26. str.expandtabs(tabsize=8):将字符串中的制表符(\t)替换为指定数量的空格。

     

    python复制代码

    s = "Hello\tWorld"
    print(s.expandtabs(4)) # 输出: Hello World
  27. str.format(*args, **kwargs):格式化字符串

# 示例 1: 使用位置参数
template = "Hello, {}. You are {} years old."
name = "Alice"
age = 30
formatted_string = template.format(name, age)
print(formatted_string)  # 输出: Hello, Alice. You are 30 years old.

# 示例 2: 使用关键字参数
template = "Hello, {name}. You are {age} years old."
formatted_string = template.format(name="Alice", age=30)
print(formatted_string)  # 输出: Hello, Alice. You are 30 years old.


# 示例 3: 混合使用位置参数和关键字参数
template = "Hello, {}. My name is {friend_name}. You are {} years old."
formatted_string = template.format("Alice", friend_name="Bob", 30)
# 注意:这种混合方式并不推荐,因为容易引起混淆。
# 更好的方式是全部使用关键字参数来保持清晰。
print(formatted_string)  # 输出: Hello, Alice. My name is Bob. You are 30 years old.

# 示例 4: 使用索引和关键字参数
template = "Person {0} is {age1} years old. Person {1} is {age2} years old."
formatted_string = template.format("Alice", "Bob", age1=30, age2=25)
print(formatted_string)  # 输出: Person Alice is 30 years old. Person Bob is 25 years old.

# 示例 5: 访问对象属性
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

alice = Person("Alice", 30)
template = "Hello, {0.name}. You are {0.age} years old."
formatted_string = template.format(alice)
print(formatted_string)  # 输出: Hello, Alice. You are 30 years old.



# 示例 6: 使用格式化规范
template = "Pi is approximately {:.2f}."
formatted_string = template.format(3.141592653589793)
print(formatted_string)  # 输出: Pi is approximately 3.14.

方法总结:

  1. str.capitalize()
    • 将字符串的第一个字符转换为大写,其余字符转换为小写。
  2. str.casefold()
    • 返回一个字符串,其中所有字符都被转换为小写,用于忽略大小写的字符串比较。
  3. str.center(width[, fillchar])
    • 返回一个原字符串居中,并使用指定的填充字符(默认为空格)填充至指定宽度的新字符串。
  4. str.count(sub[, start[, end]])
    • 返回子字符串在字符串中出现的次数,可以指定搜索的起始和结束位置。
  5. str.encode(encoding='utf-8', errors='strict')
    • 返回字符串的编码版本(字节对象)。
  6. str.endswith(suffix[, start[, end]])
    • 判断字符串是否以指定的后缀结束。
  7. str.expandtabs(tabsize=8)
    • 将字符串中的制表符(\t)转换为指定数量的空格。
  8. str.find(sub[, start[, end]])
    • 返回子字符串在字符串中最低索引(找不到返回-1)。
  9. str.format(*args, **kwargs)
    • 格式化字符串,用指定的值替换花括号 {} 中的占位符。
  10. str.format_map(mapping)
    • 类似于 format(),但使用字典作为参数。
  11. str.index(sub[, start[, end]])
    • 返回子字符串在字符串中最低索引(找不到引发 ValueError)。
  12. str.isalnum()
    • 判断字符串是否只包含字母和数字字符。
  13. str.isalpha()
    • 判断字符串是否只包含字母字符。
  14. str.isascii()
    • 判断字符串中的所有字符是否都是ASCII字符。
  15. str.isdigit()
    • 判断字符串是否只包含数字字符。
  16. str.isdecimal()
    • 判断字符串是否只包含十进制数字字符(包括全角字符等)。
  17. str.isidentifier()
    • 判断字符串是否是有效的Python标识符。
  18. str.islower()
    • 判断字符串中的所有字母是否都是小写。
  19. str.isnumeric()
    • 判断字符串是否只包含数字字符(包括全角字符和罗马数字等)。
  20. str.isprintable()
    • 判断字符串中的所有字符是否都是可打印的,并且不是控制字符。
  21. str.isspace()
    • 判断字符串是否只包含空白字符。
  22. str.istitle()
    • 判断字符串是否是标题化的(即每个单词的首字母都是大写)。
  23. str.isupper()
    • 判断字符串中的所有字母是否都是大写。
  24. str.join(iterable)
    • 将序列中的元素以指定的字符串连接生成一个新的字符串。
  25. str.ljust(width[, fillchar])
    • 返回一个原字符串左对齐,并使用指定的填充字符(默认为空格)填充至指定宽度的新字符串。
  26. str.lower()
    • 将字符串中的所有字符转换为小写。
  27. str.lstrip([chars])
    • 去除字符串左侧的空白字符(或指定的字符)。
  28. str.maketrans(intab, outtab[, transtab])
    • 创建字符映射的转换表。通常与 translate() 方法一起使用。
  29. str.partition(sep)
    • 根据指定的分隔符将字符串分割成三部分,返回一个包含分隔符的元组。
  30. str.replace(old, new[, count])
    • 将字符串中的old替换为new,可以指定替换的次数。
  31. str.rfind(sub[, start[, end]])
    • 返回子字符串在字符串中最高索引(找不到返回-1)。
  32. str.rindex(sub[, start[, end]])
    • 返回子字符串在字符串中最高索引(找不到引发 ValueError)。
  33. str.rjust(width[, fillchar])
    • 返回一个原字符串右对齐,并使用指定的填充字符(默认为空格)填充至指定宽度的新字符串。
  34. str.rpartition(sep)
    • 类似于 partition(),但从字符串的右侧开始分割。
  35. str.rsplit([sep[, maxsplit]])
    • 通过指定的分隔符从右侧开始分割字符串,可以指定分割的次数。
  36. str.rstrip([chars])
    • 去除字符串右侧的空白字符(或指定的字符)。
  37. str.split([sep[, maxsplit]])
    • 通过指定的分隔符将字符串分割成列表,可以指定分割的次数。
  38. str.splitlines([keepends])
    • 按照行分隔符将字符串分割成列表,可以保留行尾的分隔符。
  39. str.startswith(prefix[, start[, end]])
    • 判断字符串是否以指定的前缀开始。
  40. str.strip([chars])
    • 去除字符串前后的空白字符(或指定的字符)。
  41. str.swapcase()
    • 反转字符串中的大小写。
  42. str.title()
    • 将字符串中的每个单词的首字母转换为大写。
  43. str.translate(table)
    • 根据转换表替换字符串中的字符。
  44. str.upper()
    • 将字符串中的所有字符转换为大写。
  45. str.zfill(width)
    • 在字符串的左侧填充零,直到达到指定的宽度。

这些方法允许你执行各种字符串操作,包括转换、搜索、替换、分割和连接等。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值