Python----字符串

 

目录

1.字符串定义

2.字符串的大小写转换方法

3. 字符串内容对齐操作的方法

4.字符串劈分

5.字符串切片

6.格式化字符串


目录

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']

5.字符串切片

6.格式化字符串

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值