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']
相关文章
|
9天前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
191 100
|
9天前
|
开发者 Python
Python中的f-string:高效字符串格式化的利器
Python中的f-string:高效字符串格式化的利器
206 99
|
12天前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
|
12天前
|
开发者 Python
Python f-strings:更优雅的字符串格式化技巧
Python f-strings:更优雅的字符串格式化技巧
|
12天前
|
开发者 Python
Python f-string:高效字符串格式化的艺术
Python f-string:高效字符串格式化的艺术
|
23天前
|
Python
使用Python f-strings实现更优雅的字符串格式化
使用Python f-strings实现更优雅的字符串格式化
|
2月前
|
Python
Python中的f-string:更简洁的字符串格式化
Python中的f-string:更简洁的字符串格式化
213 92
|
2月前
|
数据采集 存储 数据库
Python字符串全解析:从基础操作到高级技巧
Python字符串处理详解,涵盖基础操作、格式化、编码、正则表达式及性能优化等内容,结合实际案例帮助开发者系统掌握字符串核心技能,提升文本处理与编程效率。
168 0
|
2月前
|
存储 小程序 索引
Python变量与基础数据类型:整型、浮点型和字符串操作全解析
在Python编程中,变量和数据类型是构建程序的基础。本文介绍了三种基本数据类型:整型(int)、浮点型(float)和字符串(str),以及它们在变量中的使用方式和常见操作。通过理解变量的动态特性、数据类型的转换与运算规则,初学者可以更高效地编写清晰、简洁的Python代码,为后续学习打下坚实基础。
341 0

推荐镜像

更多