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

Python中的常用字符串函数介绍

发布时间:2023-06-18 10:11:07

Python是一门强大的编程语言,它可以用于处理许多不同类型的数据,其中字符串是最常见和最重要的类型之一。字符串是一种序列,由单个字符组成,可以是字母、数字、符号或空格。在Python中,字符串具有很多有用的功能和函数,下文将介绍一些常用的字符串函数。

1. len()函数:用于获取字符串的长度

len(str)

例如:

str = "Hello World"

print(len(str))   # output: 11

2. split()函数:用于将字符串分割成一个列表

str.split(separator, maxsplit)

separator参数用于指定分隔符,maxsplit参数用于指定分割的最大次数。

例如:

str = "Hello World"

print(str.split())   # output: ['Hello', 'World']

3. join()函数:用于将一个序列中的元素用指定的分隔符连接成一个字符串

separator.join(seq)

例如:

str = ["Hello", "World"]

separator = " "

print(separator.join(str))   # output: "Hello World"

4. strip()函数:用于去除字符串两端的空格

str.strip([chars])

chars参数用于指定去除的字符,如果不指定,则默认为空格。

例如:

str = "   Hello World   "

print(str.strip())   # output: "Hello World"

5. replace()函数:用于替换字符串中的指定字符

str.replace(old, new, count)

old参数用于指定要替换的字符,new参数用于指定替换后的字符,count参数用于指定替换的次数。

例如:

str = "Hello World"

print(str.replace("o", "x"))   # output: "Hellx Wxrld"

6. lower()函数:用于将字符串所有字母转换为小写

str.lower()

例如:

str = "Hello World"

print(str.lower())   # output: "hello world"

7. upper()函数:用于将字符串所有字母转换为大写

str.upper()

例如:

str = "Hello World"

print(str.upper())   # output: "HELLO WORLD"

8. find()函数:用于查找字符串中指定字符第一次出现的位置

str.find(sub, start, end)

sub参数用于指定要查找的字符,start参数用于指定查找的起始位置,end参数用于指定查找的结束位置。

例如:

str = "Hello World"

print(str.find("o"))   # output: 4

9. startswith()函数:用于判断字符串是否以指定字符开头

str.startswith(prefix, start, end)

prefix参数用于指定要判断的前缀,start参数用于指定判断的起始位置,end参数用于指定判断的结束位置。

例如:

str = "Hello World"

print(str.startswith("H"))   # output: True

10. endswith()函数:用于判断字符串是否以指定字符结尾

str.endswith(suffix, start, end)

suffix参数用于指定要判断的后缀,start参数用于指定判断的起始位置,end参数用于指定判断的结束位置。

例如:

str = "Hello World"

print(str.endswith("d"))   # output: True

这些函数只是Python中可用的众多字符串函数中的一些常用函数。理解并掌握这些常用字符串函数可以帮助您处理和操作字符串数据更加高效和简便。