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

常用的Python字符串函数及使用方式

发布时间:2023-06-12 05:41:29

Python是一种非常流行的编程语言,它拥有非常强大的字符串处理功能。在Python中,字符串被视为不可变的序列,其函数可以轻松地操作这些序列。本文将介绍一些常用的Python字符串函数及其使用方法。

1. len()函数

len()函数用于返回字符串的长度。

使用方法:

str = "hello world"
print(len(str))

输出结果为:

11

2. find()函数

find()函数用于查找子字符串,并返回子字符串第一次出现的索引。如果未找到子字符串,则返回-1。

使用方法:

str = "hello world"
print(str.find("world"))

输出结果为:

6

3. replace()函数

replace()函数用于替换字符串中的子字符串。

使用方法:

str = "hello world"
new_str = str.replace("world", "Python")
print(new_str)

输出结果为:

hello Python

4. split()函数

split()函数用于分割字符串,返回一个包含分割后的字符串的列表。默认情况下,使用空格作为分隔符。可以指定分隔符。

使用方法:

str = "hello world"
print(str.split())

输出结果为:

['hello', 'world']

str = "hello,world"
print(str.split(","))

输出结果为:

['hello', 'world']

5. join()函数

join()函数用于将字符串的元素连接在一起,形成一个新的字符串。

使用方法:

str_list = ['hello', 'world']
new_str = ' '.join(str_list)
print(new_str)

输出结果为:

hello world

6. lower()和upper()函数

lower()和upper()函数分别用于将字符串转换为小写和大写。

使用方法:

str = "Hello World"
print(str.lower())

输出结果为:

hello world

str = "Hello World"
print(str.upper())

输出结果为:

HELLO WORLD

7. strip()函数

strip()函数用于删除字符串开头和结尾的空格。

使用方法:

str = "   hello world   "
new_str = str.strip()
print(new_str)

输出结果为:

hello world

8. isdigit()和isalpha()函数

isdigit()函数用于检查字符串是否仅由数字组成,返回布尔值。同样,isalpha()函数用于检查字符串是否仅由字母组成。

使用方法:

str = "1234"
print(str.isdigit())

输出结果为:

True

str = "hello"
print(str.isalpha())

输出结果为:

True

这些是Python中一些常用的字符串函数及其使用方法。当处理字符串时,了解这些函数的功能和如何使用它们可以帮助您更轻松地完成字符串处理任务。