Python__21--字符串对齐与拆分

简介: 字符串对齐与拆分

1 字符串对齐

默认填充空格,指定参数小于原字符串个数,则原样输出

1.1 居中对齐,center()

s='hello,world'
print(s.center(20,'*'))
#输出
#****hello,world****

1.2 左对齐,ljust

print(s.ljust(20,'*'))
#输出
#hello,world********

1.3 右对齐,rjust、zfil()

  • s.rjust()

    print(s.rjust(20,'*'))
    #输出
    #********hello,world
  • s.zfill() 只有一个个数参数,用0填充

    print(s.zfill(20,'*'))
    #输出
    #00000000hello,world
    print('-8000'.zfill(8))
    #输出
    #-00080000

测试代码:

s='hello,world'
print(s.center(20,'*'))
print(s.center(20))
print(s.ljust(20,'*') )
print(s.rjust(20,'*') )
print(s.zfill(20) )
print('-8000'.zfill(8))

测试结果:

tmpF14.png (300×227) (amazonaws.com)

2 字符串劈分

2.1 s1.split()

左侧开始分割,默认用空格分隔

s1='hello world python'
print(s1.split())    #默认在空格处分割
#输出:['hello',world','python']

s2='hello|world|python'
print(s2.split(sep='|'))    #用竖线分割
#输出:['hello',world','python']

print(s2.split(sep='|',maxsplit=1))    #按照竖线,从左开始分割一个
#输出:['hello',world|python']

2.2 s1.rsplit

右侧开始分割,默认用空格分隔

s1='hello world python'
print(s1.rsplit())    #默认在空格处分割

s2='hello|world|python'
print(s2.rsplit(sep='|'))    #用竖线分割
#输出:['hello',world','python']

print(s2.split(sep='|',maxsplit=1))    #按照竖线,从右侧开始分割一个
#输出:['hello|world','python']
相关文章
|
1月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
216 100
|
1月前
|
开发者 Python
Python中的f-string:高效字符串格式化的利器
Python中的f-string:高效字符串格式化的利器
292 99
|
1月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
|
1月前
|
开发者 Python
Python f-strings:更优雅的字符串格式化技巧
Python f-strings:更优雅的字符串格式化技巧
|
1月前
|
开发者 Python
Python f-string:高效字符串格式化的艺术
Python f-string:高效字符串格式化的艺术
|
1月前
|
Python
使用Python f-strings实现更优雅的字符串格式化
使用Python f-strings实现更优雅的字符串格式化
|
2月前
|
Python
Python中的f-string:更简洁的字符串格式化
Python中的f-string:更简洁的字符串格式化
225 92
|
14天前
|
存储 Java 索引
(Python基础)新时代语言!一起学习Python吧!(二):字符编码由来;Python字符串、字符串格式化;list集合和tuple元组区别
字符编码 我们要清楚,计算机最开始的表达都是由二进制而来 我们要想通过二进制来表示我们熟知的字符看看以下的变化 例如: 1 的二进制编码为 0000 0001 我们通过A这个字符,让其在计算机内部存储(现如今,A 字符在地址通常表示为65) 现在拿A举例: 在计算机内部 A字符,它本身表示为 65这个数,在计算机底层会转为二进制码 也意味着A字符在底层表示为 1000001 通过这样的字符表示进行转换,逐步发展为拥有127个字符的编码存储到计算机中,这个编码表也被称为ASCII编码。 但随时代变迁,ASCII编码逐渐暴露短板,全球有上百种语言,光是ASCII编码并不能够满足需求
83 3
|
2月前
|
数据采集 存储 数据库
Python字符串全解析:从基础操作到高级技巧
Python字符串处理详解,涵盖基础操作、格式化、编码、正则表达式及性能优化等内容,结合实际案例帮助开发者系统掌握字符串核心技能,提升文本处理与编程效率。
216 0

推荐镜像

更多