字符串有哪些常用方法如split()

字符串(String)在编程中非常常用,各种编程语言都提供了丰富的字符串操作方法。以下是Python中字符串的一些常用方法,包括split()方法及其它几个常用的字符串方法:

  1. split()

    • 功能:将字符串分割成子字符串列表,默认以空白字符(如空格、换行符等)作为分隔符。
    • 用法str.split(sep=None, maxsplit=-1)
    • 参数
      • sep:分隔符,默认为任何空白字符。
      • maxsplit:分割次数,默认为-1(即分割所有可能的子字符串)。
    • 示例
      s = "Hello World, this is Python"
      print(s.split())  # ['Hello', 'World,', 'this', 'is', 'Python']
      print(s.split(", "))  # ['Hello World', 'this is Python']
      print(s.split(", ", 1))  # ['Hello World', 'this is Python']
      
  2. join()

    • 功能:将序列中的元素以指定的字符连接生成一个新的字符串。
    • 用法str.join(iterable)
    • 参数
      • iterable:要连接的元素序列,通常是列表或元组。
    • 示例
      words = ['Hello', 'World', 'this', 'is', 'Python']
      print(" ".join(words))  # 'Hello World this is Python'
      print(", ".join(words))  # 'Hello, World, this, is, Python'
      
  3. strip()

    • 功能:去除字符串首尾的指定字符(默认为空白字符)。
    • 用法str.strip([chars])
    • 参数
      • chars:要去除的字符集合,默认为空白字符。
    • 示例
      s = "   Hello World   "
      print(s.strip())  # 'Hello World'
      print(s.strip(" "))  # 'Hello World'
      print(s.strip(" Heo"))  # 'rld   '
      
  4. find()

    • 功能:返回子字符串在字符串中最低索引(起始位置),如果找不到则返回-1。
    • 用法str.find(sub[, start[, end]])
    • 参数
      • sub:要查找的子字符串。
      • start:查找的起始位置。
      • end:查找的结束位置。
    • 示例
      s = "Hello World, this is Python"
      print(s.find("World"))  # 6
      print(s.find("world"))  # -1
      print(s.find("is", 7, 15))  # -1
      
  5. replace()

    • 功能:将字符串中的某些部分替换为另一个字符串。
    • 用法str.replace(old, new[, count])
    • 参数
      • old:要被替换的子字符串。
      • new:用于替换的新字符串。
      • count:替换次数,默认为-1(即替换所有可能的子字符串)。
    • 示例
      s = "Hello World, this is Python"
      print(s.replace("World", "Python"))  # 'Hello Python, this is Python'
      print(s.replace("is", "are", 1))  # 'Hello World, this are Python'
      
  6. upper()lower()

    • 功能:将字符串转换为大写或小写。
    • 用法str.upper()str.lower()
    • 示例
      s = "Hello World"
      print(s.upper())  # 'HELLO WORLD'
      print(s.lower())  # 'hello world'
      
  7. startswith()endswith()

    • 功能:检查字符串是否以指定的前缀或后缀结束。
    • 用法str.startswith(prefix[, start[, end]])str.endswith(suffix[, start[, end]])
    • 参数
      • prefix/suffix:要检查的前缀/后缀。
      • start:检查的起始位置。
      • end:检查的结束位置。
    • 示例
      s = "Hello World"
      print(s.startswith("Hello"))  # True
      print(s.endswith("World"))  # True
      print(s.startswith("hello"))  # False
      

这些方法只是Python中字符串方法的冰山一角,但它们是最常用和最有用的方法之一。通过这些方法,你可以轻松地对字符串进行各种操作和处理。

Python的其他常用方法

Python中除了之前提到的split()等方法外,还有许多其他常用的字符串方法。以下是一些额外的常用字符串方法及其简要说明:

  1. capitalize()

    • 功能:将字符串的第一个字符转换为大写,其余字符转换为小写。
    • 示例:"hello world".capitalize() 返回 'Hello world'
  2. title()

    • 功能:将字符串中的每个单词的首字母转换为大写,其余字符转换为小写。
    • 示例:"hello world, this is python".title() 返回 'Hello World, This Is Python'
  3. strip([chars])lstrip([chars])rstrip([chars])

    • 功能:分别去除字符串两侧、左侧或右侧的指定字符(默认为空白字符)。
    • 示例:" hello world ".strip() 返回 'hello world'
  4. count(sub[, start[, end]])

    • 功能:返回子字符串在字符串中出现的次数,可以指定搜索的起始和结束位置。
    • 示例:"hello hello".count("hello") 返回 2
  5. find(sub[, start[, end]])rfind(sub[, start[, end]])

    • 功能:find() 返回子字符串在字符串中第一次出现的索引,rfind() 返回最后一次出现的索引。
    • 示例:"hello world".find("world") 返回 6
  6. index(sub[, start[, end]])rindex(sub[, start[, end]])

    • 功能:与find()rfind()类似,但找不到子字符串时会引发ValueError异常。
    • 示例:"hello world".index("world") 返回 6
  7. expandtabs(tabsize=8)

    • 功能:将字符串中的制表符(\t)转换为指定数量的空格。
    • 示例:"hello\tworld".expandtabs(4) 返回 'hello world'
  8. zfill(width)

    • 功能:在字符串的左侧填充零,直到字符串的总长度达到指定的宽度。
    • 示例:"42".zfill(5) 返回 '00042'
  9. swapcase()

    • 功能:将字符串中的大写字母转换为小写字母,小写字母转换为大写字母。
    • 示例:"Hello World".swapcase() 返回 'hELLO wORLD'
  10. translate(table[, deletechars])maketrans(intab, outab[, deletechars])

    • 功能:translate() 使用maketrans()创建的映射表或字典替换字符串中的字符。maketrans() 创建字符映射的转换表。
    • 示例:
      table = str.maketrans("aeiou", "12345")
      "hello world".translate(table)
      
      返回 'h2ll3 w4rld'
  11. isalnum()isalpha()isdigit()isspace()istitle()islower()isupper()

    • 功能:这些方法用于检查字符串是否满足特定的条件,如是否全是字母和数字、是否全是字母、是否全是数字、是否全是空白字符、是否每个单词的首字母都大写、是否全为小写字母、是否全为大写字母等。
    • 示例:"Hello123".isalnum() 返回 True"Hello".isalpha() 返回 True
  12. partition(sep)rpartition(sep)

    • 功能:以指定的分隔符分割字符串,并返回包含分隔符的三元组。partition() 从左开始分割,rpartition() 从右开始分割。
    • 示例:"hello world".partition(" ") 返回 ('hello', ' ', 'world')
  13. splitlines([keepends])

    • 功能:按行分割字符串,并返回一个列表。如果keependsTrue,则保留行尾的分隔符。
    • 示例:"hello\nworld\n".splitlines() 返回 ['hello', 'world']

这些方法提供了丰富的字符串处理能力,使Python成为处理文本数据的强大工具。

posted @   nxhujiee  阅读(63)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示