Python中的字符串处理相关函数
Python中提供了很多字符串处理相关的函数,下面列举一些比较常用的:
1. find()函数
该函数用于查找一个字符串中是否包含指定的子串,如果存在则返回子串的起始位置,否则返回-1。
语法:字符串.find(str, [start, [end]])
其中,str为要查找的子串,start为开始查找的位置(默认为0),end为结束查找的位置(默认为len(str))。
示例代码:
string = 'hello world'
index = string.find('world')
print(index) # 输出6
2. split()函数
该函数用于将一个字符串按照指定的分隔符进行分割,返回分割后得到的字符串列表。
语法:字符串.split([sep, [maxsplit]])
其中,sep为分隔符,默认为所有空字符,如空格、换行、制表符等;maxsplit为最大分割次数,可选参数。
示例代码:
string = 'hello,world'
list = string.split(',')
print(list) # 输出['hello', 'world']
3. join()函数
该函数用于将一个由字符串组成的列表连接成一个字符串,连接方式为指定的分隔符。
语法:分隔符.join(字符串列表)
示例代码:
list = ['hello', 'world'] string = '-'.join(list) print(string) # 输出'hello-world'
4. replace()函数
该函数用于将一个字符串中指定的子串替换成目标子串,返回替换后得到的新字符串。
语法:字符串.replace(old, new, count)
其中,old为要替换的子串,new为目标子串,count为最大替换次数,可选参数。
示例代码:
string = 'hello world'
new_string = string.replace('world', 'python')
print(new_string) # 输出'hello python'
5. strip()函数
该函数用于去除一个字符串首尾的指定字符(默认为空格),返回去除后得到的新字符串。
语法:字符串.strip([chars])
其中,chars为要去除的字符集合,默认为空格。
示例代码:
string = ' hello world ' new_string = string.strip() print(new_string) # 输出'hello world'
6. isdigit()函数
该函数用于判断一个字符串是否只包含数字字符,返回True或False。
示例代码:
string1 = '12345' string2 = '12.345' print(string1.isdigit()) # 输出True print(string2.isdigit()) # 输出False
7. upper()和lower()函数
这两个函数分别用于将一个字符串中的所有字符转换成大写和小写,返回转换后得到的新字符串。
语法:字符串.upper()和字符串.lower()
示例代码:
string = 'Hello World' upper_string = string.upper() lower_string = string.lower() print(upper_string) # 输出'HELLO WORLD' print(lower_string) # 输出'hello world'
以上是Python中常用的一些字符串处理函数,还有其他一些函数如center()、ljust()、rjust()等也可以参考Python官方文档来学习和使用。
