欢迎访问宙启技术站
智能推送

Python内置函数:字符串处理函数及用法

发布时间:2023-06-24 22:48:15

Python是一种高级编程语言,它为程序员提供了一系列内置函数来处理字符串。处理字符串是编程中经常遇到的任务之一,例如查找、替换、格式化等。本文将介绍一些常见的 Python 内置字符串处理函数及其用法。

1. len()

len() 函数用于获取字符串长度。它接受一个字符串作为参数,并返回字符串中字符的个数。

string = "Hello World"
print(len(string))
# 输出:11

2. split()

split() 函数用于将字符串拆分为多个子串。它接受一个分隔符作为参数,并返回一个包含子串的列表。默认的分隔符是空格。

string = "Hello World"
words = string.split()
print(words)
# 输出:['Hello', 'World']

string = "apple,banana,orange"
fruits = string.split(",")
print(fruits)
# 输出:['apple', 'banana', 'orange']

3. join()

join() 函数用于将多个字符连接为一个字符串。它接受一个可迭代对象作为参数,并以字符串作为分隔符。

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

fruits = ['apple', 'banana', 'orange']
string = ",".join(fruits)
print(string)
# 输出:apple,banana,orange

4. replace()

replace() 函数用于替换字符串中的指定部分。它接受两个参数:需要替换的子串和替换成的新子串。

string = "Hello World"
new_string = string.replace("World", "Python")
print(new_string)
# 输出:Hello Python

5. startswith() 和 endswith()

startswith() 函数用于检查字符串是否以指定子串开始。它接受一个参数:指定的子串。endswith() 函数用于检查字符串是否以指定子串结尾。

string = "Hello World"
if string.startswith("Hello"):
    print("字符串以 Hello 开头")
if string.endswith("World"):
    print("字符串以 World 结尾")
# 输出:字符串以 Hello 开头
# 输出:字符串以 World 结尾

6. strip()

strip() 函数用于去除字符串首尾的指定字符。它接受一个可选参数:指定需要去除的字符,默认为空格。

string = "   hello   "
new_string = string.strip()
print(new_string)
# 输出:hello

string = "||hello||"
new_string = string.strip("|")
print(new_string)
# 输出:hello

这些都是 Python 内置的常用字符串处理函数。通过这些函数,你可以更方便地对字符串进行处理。当然,Python 还有很多其他处理字符串的方法,不过这些方法已经足够你完成大多数字符串处理任务了。