Python-常用字符串方法

当涉及到Python中字符串的方法和函数时,有许多内置工具可供使用。以下是一些常用的字符串方法和函数,以及它们的用法和示例:

常用字符串方法

  1. str.capitalize():

    • 将字符串的第一个字符转换为大写,其余字符转换为小写。
    s = "hello, world"
    print(s.capitalize())  # 输出: "Hello, world"
    
  2. str.upper():

    • 将字符串中的所有字符转换为大写。
    s = "hello, world"
    print(s.upper())  # 输出: "HELLO, WORLD"
    
  3. str.lower():

    • 将字符串中的所有字符转换为小写。
    s = "HELLO, WORLD"
    print(s.lower())  # 输出: "hello, world"
    
  4. str.isupper():

    • 检查字符串中的所有字符是否都是大写。
    s = "HELLO, WORLD"
    print(s.isupper())  # 输出: True
    
  5. str.islower():

    • 检查字符串中的所有字符是否都是小写。
    s = "hello, world"
    print(s.islower())  # 输出: True
    
  6. str.isdigit():

    • 检查字符串中的所有字符是否都是数字字符。
    s = "123"
    print(s.isdigit())  # 输出: True
    
  7. str.split(sep=None):

    • 将字符串分割成子字符串列表。可以通过sep参数指定分隔符,默认情况下使用空格作为分隔符。
    s = "hello, world"
    print(s.split())  # 输出: ['hello,', 'world']
    
  8. str.strip(chars=None):

    • 返回一个去除了开头和结尾指定字符chars的字符串副本。如果未指定chars,则默认删除空白字符。
    s = "  hello, world  "
    print(s.strip())  # 输出: "hello, world"
    
  9. str.replace(old, new):

    • 将字符串中的所有子字符串old替换为new
    s = "hello, world"
    print(s.replace("hello", "hi"))  # 输出: "hi, world"
    
  10. str.join(iterable):

    • 将可迭代对象iterable中的所有字符串连接成一个字符串,使用当前字符串作为分隔符。
    s = ","
    print(s.join(["apple", "banana", "cherry"]))  # 输出: "apple,banana,cherry"
    
  11. str.startswith(prefix)str.endswith(suffix):

    • 检查字符串是否以指定的前缀或后缀开始或结束,返回TrueFalse
    s = "hello, world"
    print(s.startswith("hello"))  # 输出: True
    print(s.endswith("world"))    # 输出: True
    
  12. str.find(sub)str.index(sub):

    • 在字符串中搜索子字符串sub,并返回第一个匹配项的索引。如果没有找到,find()返回-1,index()引发ValueError异常。
    s = "hello, world"
    print(s.find("world"))  # 输出: 7
    print(s.index("world")) # 输出: 7
    
  13. str.count(sub):

    • 返回子字符串sub在字符串中出现的次数。
    s = "hello, world"
    print(s.count("l"))  # 输出: 3
    
  14. str.format():

    • 格式化字符串,用参数替换字符串中的占位符。
    name = "Alice"
    age = 30
    print("My name is {} and I am {} years old.".format(name, age))
    
  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值