目录
1.字符串定义
- Python是一个不可变的字符序列
- 字符串的定义:'python',"python",''' python''',
a = 'python' b = "python" c ='''python'''
打印结果如下:
a = python
b = python
c = python
2.字符串的大小写转换方法
upper()把字符串中所有字符转换为大写
lower()把字符串中所有字符转换成小写
swapcase()把字符串中所有大写字母转换成小写字母,把所有小写字母转换成大写字母
title()把每个单词的第一个字符转换为大写,把每个单词的剩余字符转换为小写
s ='hello,python'
a =s.upper()#把字符串中所有字符转换为大写
print(s,id(s))
print(a,id(a))
print(s.lower(),id(s.lower()))#把字符串中所有字符转换成小写
s1 ='hello,Python'
print(s1.swapcase()#把字符串中所有大写字母转换成小写字母,把所有小写字母转换成大写字母
print(s1.title())#把每个单词的第一个字符转换为大写,把每个单词的剩余字符转换为小写
3. 字符串内容对齐操作的方法
- center()居中对齐
- ljust()左对齐
- rjust()右对齐
- sfill()右对齐,使用0进行填充
s = 'hello,Python'
'''居中对齐'''
print(s.center(20,'='))
'''左对齐'''
print(s.ljust(20,'#'))
print(s.ljust(20))
print(s.ljust(10))
'''右对齐'''
print(s.rjust(20,'&'))
print(s.rjust(20))
print(s.rjust(10))
'''右对齐,使用0进行填充'''
print(s.zfill(20))
print(s.zfill(10))
print('-8929'.zfill(8))
打印结果
====hello,Python====
hello,Python########
hello,Python
hello,Python
&&&&&&&&hello,Python
hello,Python
hello,Python
00000000hello,Python
hello,Python
-0008929
4.字符串劈分
split()从字符串的左边开始劈分,默认的劈分字符是空格字符串,返回的值都是一个列表
s = 'hello world python' lst = s.split()#未指定分隔符 print(lst)#['hello', 'world', 'python'] s1 = 'hello-world-python' lst1 = s1.split(sep='-')#分隔符为- print(lst1)#['hello', 'world', 'python'] lst1 = s1.split(sep='-',maxsplit=1) print(lst1)#['hello', 'world-python']
rsplit() 从字符串的右边开始劈分,默认的劈分字符是空格字符串,返回的值都是一个列表
s = 'hello world python' s1 = 'hello-world-python' a = s.rsplit() print(a)#['hello', 'world', 'python'] print(s1.rsplit('-'))#['hello', 'world', 'python'] print(s1.rsplit(sep='-',maxsplit=1))#['hello-world', 'python']