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

Python中常用的字符串函数:split()、join()、strip()等

发布时间:2023-06-12 17:04:35

Python中有许多字符串处理函数,包括split()、join()、strip()等,它们在日常工作中经常被用到。下面将详细介绍这些常用的字符串函数。

split()

split()函数用于将字符串分割成一个列表。可以使用split()函数来分割字符串,切割规则可以是任意你需要的字符。例如:

str = "Python is fun"
list = str.split()
print(list)

这会输出:

['Python', 'is', 'fun']

split()默认按照空格分割字符串,并返回一个列表。如果你想要按照其他字符进行分割,可以在split()函数中加入相应的分隔符,例如:

str = "apple,banana,orange"
list = str.split(',')
print(list)

这会输出:

['apple', 'banana', 'orange']

join()

join()函数就是一种将字符串列表连接成一个字符串的方法。利用join()函数,可以将一个列表或元组中的所有元素按照指定的分隔符连接成一个字符串。例如:

list = ['apple','banana','orange']
str = ','.join(list)
print(str)

这会输出:

'apple,banana,orange'

在这个例子中,join()函数接受一个列表作为输入,将其连接成一个由逗号分隔的字符串,并将结果打印出来。

strip()

strip()函数可以去除字符串的开头和结尾处的空白字符。空白字符包括空格、制表符和换行符等。例如:

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

这会输出:

'hello world'

该函数还可以接受一个参数,指定需要去除的字符,例如:

str = "-----hello world-----"
print(str.strip('-'))

这会输出:

'hello world'

replace()

replace()函数用于将指定的字符串替换为另一个字符串。例如:

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

这会输出:

hello Python

该函数还可以接受两个参数,分别指定要替换的子字符串和替换为的字符串。例如:

str = "Hello World"
str = str.replace("World", "Python", 1)
print(str)

这会输出:

'Hello Python'

这里的1表示只替换 个出现的子字符串。

lower()和upper()

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

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

这会输出:

'hello world'

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

这会输出:

'HELLO WORLD'

startswith()和endswith()

startswith()和endswith()函数用于检查字符串是否以指定的字符串开头或结尾。例如:

str = "Hello World"
print(str.startswith("Hello"))
print(str.endswith("World"))

这会输出:

True
True

以上就是Python中常用的字符串函数的介绍,这些函数在日常开发过程中非常实用,使用它们可以大大提高编程效率。