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

Python的常用字符串函数

发布时间:2023-05-26 00:38:06

Python是一种高级的简单易学的语言,它提供了许多内置函数,使编写程序变得更加简单和快捷。在Python中,字符串是一种重要的数据类型。在许多情况下,处理字符串是必不可少的。Python提供了许多内置函数来操作字符串,以便将其用于程序中。在这里,我们将讨论Python中常用的字符串函数。

1、find()函数

find()函数用于查找字符串中给定的子字符串。如果找到子字符串,则返回该子字符串的索引,如果该字符串不存在,则返回-1。

string = "hello, world"
print(string.find("world"))  # 7
print(string.find("Python"))  # -1

2、replace()函数

replace()函数用于用给定的新子字符串替换原始字符串中的旧子字符串。

string = "hello, world"
new_string = string.replace("world", "Python")
print(new_string)  # hello, Python

3、split()函数

split()函数用于将字符串分割为列表。

string = "python is a high-level programming language"
new_string = string.split()
print(new_string)  # ['python', 'is', 'a', 'high-level', 'programming', 'language']

4、join()函数

join()函数用于将一个列表中的项连接为一个字符串。

words = ['python', 'is', 'a', 'high-level', 'programming', 'language']
new_string = ' '.join(words)
print(new_string)  # 'python is a high-level programming language'

5、lower()函数和upper()函数

lower()函数用于将字符串中的所有字符转换为小写字母,upper()函数将字符串中的所有字符转换为大写字母。

string = "Hello, World"
new_string = string.lower()
print(new_string)  # hello, world

new_string = string.upper()
print(new_string)  # HELLO, WORLD

6、strip()函数

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

string = "      Hello, World       "
new_string = string.strip()
print(new_string)  # Hello, World

7、isdigit()函数和isalpha()函数

isdigit()函数用于检查字符串是否只包含数字,isalpha()函数用于检查字符串是否只包含字母。

string_1 = "123"
string_2 = "abc"
print(string_1.isdigit())  # True
print(string_2.isdigit())  # False

print(string_1.isalpha())  # False
print(string_2.isalpha())  # True

8、startswith()函数和endswith()函数

startswith()函数用于检查字符串是否以给定的子字符串开头,endswith()函数用于检查字符串是否以给定的子字符串结尾。

string = "Hello, World"
print(string.startswith("Hello"))  # True
print(string.startswith("World"))  # False

print(string.endswith("World"))  # True
print(string.endswith("Hello"))  # False

9、count()函数

count()函数用于计算字符串中给定子字符串出现的次数。

string = "google.com"
print(string.count("o"))  # 2
print(string.count("go"))  # 1
print(string.count("com"))  # 1

10、len()函数

len()函数用于计算给定字符串的长度。

string = "Hello, World"
print(len(string))  # 13

总之,以上是Python中常用的字符串函数。这些函数可以加速代码开发,使编写Python程序变得更加容易和快捷。熟悉这些函数,可以更好地操作和控制字符串,同时也可以更好地开发程序。