文章目录
- 前言
- python简单字符串操作
- 一.获取长度:len
- 二.查找内容:find,index,rfind,rindex
- 三.判断:startswith,endswith,isalpha,isdigit,isalnum,isspace,isidentifier,islower,isupper
- 四.计算出现次数:count
- 五.替换内容:replace
- 六.切割字符串:split,rsplit,splitlines,partition,rpartition
- 七.修改大小写:capitalize,title,upper,lower
- 八.空格处理:ljust,rjust,center,strip,lstrip,rstrip
- 九.字符串拼接: join
- 十.输出指定内容:format
- 十一.将字典中的参数传进字符串:format_map
- 总结
前言
本文是我通过学习与积累,搜集资料所得,方便以后学习使用,希望能给你也能带来帮助~
python简单字符串操作
一.获取长度:len
len函数:
说明:输出对象的长度
语法:
len(s)
举个例子:
str="hello"
print(len(str))#字符串长度
#输出5
l = [1,2,3,4,5,6]
print(len(l))#列表长度
#输出6
二.查找内容:find,index,rfind,rindex
1.find函数:
说明:返回指定字符串的首索引,没有则返回-1
语法:
str1.find(str2, begin=0, end=len(str1))
-
str1为父字符串
-
str2为子字符串
-
begin为开始的索引,默认为0
-
end为结束的索引,默认为父字符串的长度
举个例子:
str1 = "this is a string example"
str2 = "exam"
print(str1.find(str2))
print(str1.find(str2, 10))
print(str1.find(str2, 40))
输出:
17
17
-1
2.index函数:
说明:和find函数使用一模一样,但是搜索不到时会引发异常。没有返回值
举个例子:
str1 = "this is a string example"
str2 = "exam"
print(str1.index(str2))
print(str1.index(str2, 10))
print(str1.index(str2, 40))
输出:
17
17
Traceback (most recent call last):
File "c:\Users\hp\Desktop\python\python学习.py", line 6, in <module>
print(str1.index(str2, 40))
ValueError: substring not found
3.rfind函数:
说明:寻找子字符串最后一次出现的索引,找不到则返回-1
语法:
str1.rfind(str2, begin=0, end=len(str1))
举个例子:
str1 = "Hello, welcome to my world."
str2 = "e"
str3 = "Helloe"
print(str1.rfind(str2))
print(str1.rfind(str3))
输出:
13
-1
4.rindex函数:
说明:和rfind函数用法一样,找不到时报错
举个例子:
str1 = "Hello, welcome to my world."
str2 = "z"
print(str1.rindex(str2))
输出:
Traceback (most recent call last):
File "c:\Users\hp\Desktop\python\python学习.py", line 3, in <module>
print(str1.rindex(str2))
ValueError: substring not found
三.判断:startswith,endswith,isalpha,isdigit,isalnum,isspace,isidentifier,islower,isupper
1.startswith函数:
说明:检查父字符串是否以子字符串开头,返回值为True或False
语法:
str1.startswith(str2, beg=0,end=len(str1));
参数和上面find函数一样!
举个例子:
str1 = "this is a string example"
str2 = "this"
str3 = "is"
print(str1.startswith(str2 ))
print(str1.startswith( str3, 2, 4 ))
print(str1.startswith( str2, 2, 4 ))
输出:
True
True
False
2.endswith函数:
说明:检查父字符串是否以子字符串结尾,返回值为True或False
举个例子:
str1 = "this is a string example"
str2 = "example"
str3 = "is"
print(str1.endswith(str2 ))
print(str1.endswith( str3, 2, 4 ))
print(str1.endswith( str2, 2, 4 ))
输出:
True
True
False
3.isalpha函数:
说明:判断字符串是否都是字母,返回值为True或False
举个例子:
str1 = "python"
print (str1.isalpha())
str2 = "python学习"
print(str2.isalpha())
str3="pyhton3.9.5"
print(str3.isalpha())
str4 = "python学习"
print(str4.encode('utf-8').isalpha())
输出:
True
True
False
False
细心的小伙伴可以发现,这里汉字识别不出来,也会当作字母处理。但是对其进行编码处理就能识别出来啦!
4.isdigit函数:
说明:判断字符串是否都是数字,返回值为True或False
举个例子:
str1 = "123456"
print (str1.isdigit())
str2 = "python3.9.5"
print (str2.isdigit())
输出:
True
False
5.isalnum函数:
说明:判断字符串是否都是数字和字母,返回值为True或False
举个例子:
str1 = "python3"
print (str1.isalnum())
str2 = "python3.9.5"#有标点,有空格也不行哦~
print (str2.isalnum())
输出:
True
False
6.isspace函数:
说明:判断字符串是否都是空格,返回值为True或False
举个例子:
str1 = " "
print (str1.isspace())
str2 = "python "
print (str2.isspace())
输出:
True
False
7.isidentifier函数:
说明:如果字符串是有效标识符,则 isidentifier() 方法返回 True,否则返回 False。
如果字符串仅包含字母数字字母(a-z)和(0-9)或下划线(_),则该字符串被视为有效标识符。有效的标识符不能以数字开头或包含任何空格。
举个例子:
str1 = "MyFolder"
str2 = "Demo002"
str3 = "2bring"
str4 = "my demo"
print(str1.isidentifier())
print(str2.isidentifier())
print(str3.isidentifier())
print(str4.isidentifier())
输出:
True
True
False
False
8.islower函数:
说明:判断字符串是否都是小写字母,返回值为True或False
举个例子:
str1 = "python"
print (str1.islower())
str2 = "Python"
print (str2.islower())
输出:
True
False
9.isupper函数:
说明:判断字符串是否都是大写字母,返回值为True或False
举个例子:
str1 = "PYTHON"
print (str1.isupper())
str2 = "Python"
print (str2.isupper())
输出:
True
False
四.计算出现次数:count
count函数:
说明:统计字符串里某个字符出现的次数,可以选择字符串索引的起始位置和结束位置。
语法:
str1.count(str2, start,end)
举个例子:
str1 = "I love python,I am learning python"
str2 = " "
str3 = "I"
str4 = "I "
print(str1.count(str2)) #star 和end 为默认参数
print(str1.count(str3,2)) # star值为2,end值为默认参数
print(str1.count(str3,2,5)) #star值为2,end值为5
print(str1.count(str4)) #多字符统计
输出:
5
1
0
2
五.替换内容:replace
replace函数:
说明:把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
语法:
str.replace(old, new[, max])
举个例子:
str1 = "This is a string example. This is really string"
str2 = "is"
str3 = "was"
print(str1.replace(str2, str3))
print(str1.replace(str2, str3, 3))
输出:
Thwas was a string example. Thwas was really string
Thwas was a string example. Thwas is really string
六.切割字符串:split,rsplit,splitlines,partition,rpartition
1.split函数:
说明:通过指定分隔符对字符串进行切片拆分成列表,如果参数 num 有指定值,则分隔 num+1 个子字符串
语法:
str.split(str="", num=-1)
- str – 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
- num – 分割次数。默认为 -1, 即分隔所有。
举个例子:
str = "Line1-abcdef \nLine2-abc \nLine4-abcd"
print(str.split( )) # 以空字符为分隔符,包含 \n
print(str.split(' ', 1 )) # 以空格为分隔符,分隔成两个
输出:
['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
['Line1-abcdef', '\nLine2-abc \nLine4-abcd']
2.rsplit函数:
说明:从右侧开始将字符串拆分为列表。(右侧!!!)
语法:
str.rsplit(str="", num=-1)
举个例子:
str = "Line1-abcdef \nLine2-abc \nLine4-abcd"
print(str.split( ))
print(str.split(' ', 1 ))
输出:
['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
['Line1-abcdef \nLine2-abc', '\nLine4-abcd']
3.splitlines函数:
说明:按照行(’\r’, ‘\r\n’, \n’)分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。
语法:
str.splitlines([keepends])
举个例子:
str1 = 'ab c\n\nde fg\rkl\r\n'
print(str1.splitlines())
str2 = 'ab c\n\nde fg\rkl\r\n'
print(str2.splitlines(True))
输出:
['ab c', '', 'de fg', 'kl']
['ab c\n', '\n', 'de fg\r', 'kl\r\n']
4.partition函数:
说明:根据指定的分隔符将字符串进行分割,如果字符串包含指定的分隔符,则返回一个三元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串。
语法:
str1.partition(str2)
举个例子:
str1 = "python3.9.5"
str2 = "."
print(str1.partition(str2))
输出:
('python3', '.', '9.5')
5.rpartition函数:
说明:与partition用法相同,唯一区别为这个函数是从右开始
语法:
str1.rpartition(str2)
举个例子:
str1 = "python3.9.5"
str2 = "."
print(str1.rpartition(str2))
输出:
('python3.9', '.', '5')
七.修改大小写:capitalize,title,upper,lower
1.capitalize函数:
说明: 将字符串的第一个字母变成大写,其他字母变小写。
语法:
str.capitalize()
举个例子:
str = "python3.9.5"
print(str.capitalize())
输出:
Python3.9.5
2.title函数:
说明: 返回"标题化"的字符串,就是说所有单词都是以大写开始,其余字母均为小写
语法:
str.title()
举个例子:
str = "i love python"
print(str.title())
输出:
I Love Python
3.upper函数:
说明: 将字符串中的小写字母转为大写字母。
语法:
str.upper()
举个例子:
str = "i love python"
print(str.upper())
输出:
I LOVE PYTHON
4.lower函数:
说明: 将字符串中的大写字母转为小写字母。
语法:
str.lower()
举个例子:
str = "I Love Python"
print(str.lower())
输出:
i love python
八.空格处理:ljust,rjust,center,strip,lstrip,rstrip
1.ljust函数:
说明:返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。
语法:
str.ljust(width[, fillchar])
-
width – 指定字符串长度。
-
fillchar – 填充字符,默认为空格。
举个例子:
str = "this is a string example"
print(str.ljust(5, '0'))
print(str.ljust(30, '0'))
输出:
this is a string example
this is a string example000000
2.rjust函数:
说明:返回一个原字符串右对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。
语法:
str.rjust(width[, fillchar])
举个例子:
str = "this is a string example"
print(str.rjust(5, '0'))
print(str.rjust(30, '0'))
输出:
this is a string example
000000this is a string example
3.center函数:
说明:返回一个原字符串居中,并使用空格填充(两头填充,单数前面多1)至长度 width 的新字符串,如果指定的长度小于原字符串的长度则返回原字符串。
语法:
str.center(width[, fillchar])
举个例子:
str = "this is a string example"
print(str.center(5, '0'))
print(str.center(30, '0'))
print(str.center(31, '0'))
输出:
this is a string example
000this is a string example000
0000this is a string example000
4.strip函数:
说明:移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
**注意:**该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。
语法:
str.strip([chars])
举个例子:
str = "00000003210csdn01230000000"
print (str.strip( '0' )) # 去除首尾字符 0
str2 = " csdn "; # 去除首尾空格
print (str2.strip())
str = "3210csdn0123"
print (str.strip( '0' ))
输出:
3210csdn0123
csdn
3210csdn0123
5.lstrip函数:
说明:移除字符串左侧指定的字符(默认为空格或换行符)或字符序列。
语法:
str.lstrip([chars])
举个例子:
str = "00000003210csdn01230000000"
print (str.lstrip( '0' )) # 去除首尾字符 0
str2 = " csdn "; # 去除首尾空格
print (str2.lstrip())
str = "3210csdn0123"
print (str.lstrip( '0' ))
输出:
3210csdn01230000000
csdn
3210csdn0123
6.rstrip函数:
说明:移除字符串右侧指定的字符(默认为空格或换行符)或字符序列。
语法:
str.rstrip([chars])
举个例子:
str = "00000003210csdn01230000000"
print (str.rstrip( '0' )) # 去除首尾字符 0
str2 = " csdn "; # 去除首尾空格
print (str2.rstrip())
str = "3210csdn0123"
print (str.rstrip( '0' ))
输出:
00000003210csdn0123
csdn#这里的空格已经删掉了
3210csdn0123
九.字符串拼接: join
join函数:
说明: 连接字符串数组,将字符串、元组、列表中的元素以指定的字符(分隔符)连接生成一个新的字符串
语法:
str.join(sequence)
举个例子:
str = "-"
seq = ("a", "b", "c") # 字符串序列
print(str.join( seq ))
输出:
a-b-c
十.输出指定内容:format
format函数:
说明:增强字符串格式化的功能,基本语法是通过 {} 和 : 来代替以前的 % 。
举个例子:
print("网站名:{name}, 地址 {url}".format(name="csdn", url="www.csdn.com"))
# 通过字典设置参数
site = {"name": "csdn", "url": "www.csdn.com"}
print("网站名:{name}, 地址 {url}".format(**site))
# 通过列表索引设置参数
list = ['csdn', 'www.csdn.com']
print("网站名:{0[0]}, 地址 {0[1]}".format(list)) # "0" 是必须的
输出:
网站名:csdn, 地址 www.csdn.com
网站名:csdn, 地址 www.csdn.com
网站名:csdn, 地址 www.csdn.com
十一.将字典中的参数传进字符串:format_map
format_map函数:
说明:使用提供的映射中的替换返回字符串的格式化版本。 替换参数出现在字符串中,并用花括号({})标识。
语法:
str.format_map(map)
举个例子:
str = 'My name is {name} and I am a {job_title}'
dict = {'name': 'Pan', 'job_title': 'Software Engineer'}
print(str.format_map(dict))
print(str.format(**dict))
输出:
My name is Pan and I am a Software Engineer
My name is Pan and I am a Software Engineer
总结
看到这里点个赞支持一下吧~