6

字符串对齐,删除字符串中不需要的内容,格式化打印字符

 3 years ago
source link: https://blog.csdn.net/hmh4640219/article/details/112608582
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

删除字符串中不需要的内容

1、strip()方法

strip:默认是去掉首尾的空白字符,但是也可以指定其他字符;
lstrip:只去掉左边的;
rstrip:只去掉右边的;

print('+++apple    '.strip()) # '+++apple'
print('+++apple    '.lstrip('+')) # 'apple    '
print('   apple    '.rstrip()) # '   apple'

这个只能去除首尾的,如果想去除中间的字符,可以使用倒replace()方法

2、replace()方法

replace:将字符串中所有需要替换的字符替换成指定的内容,如果指定次数count,则替换不会超过count次;原来的字符串不会改变,而是生成一个新的字符串来保存替换后的结果。

word = 'he22222222o'
m = word.replace('2', 'x', 4)
n = word.replace('2', 'x')
print(word) # he22222222o
print(m) # hexxxx2222o
print(n) # hexxxxxxxxo
print(word.replace('2','+-'))# he+-+-+-+-+-+-+-+-o

z = 'hello     world'
print(z.replace(' ',''))# helloworld

字符串对齐

ljust(width,fillchar) :返回一个左对齐的长度为width的字符串,要是字符串长度小于width则在右边用所给填充字符补齐
rjust(width,fillchar) :右对齐,同上
center(width,fillchar):居中,同上

print('hello'.ljust(10, '+'))# hello+++++
print('hello'.rjust(10))# '     hello'
print('hello'.center(10, '='))# ==hello===

format()函数

‘<’:左对齐,右补齐
‘>’:右对齐,左补齐
‘^’:居中,左右补齐
默认也是使用空格补齐,可以在这三个符号前给定字符,作为填充字符

text = 'hihi'
print(format(text, '>20'))# '                hihi'
print(format(text, '+<20'))# 'hihi++++++++++++++++'
print(format(text, '-^20'))# '--------hihi--------'

格式化打印字符

f-string:建议使用

name = '张三'
age = 18
print(f'我叫{name},今年{age}岁')# 我叫张三,今年18岁

: 号后面带填充的字符,只能是一个字符,多了会报错,不指定的话默认是用空格填充;
b、d、o、x 分别是二进制、十进制、八进制、十六进制;
.nf保留n位小数
.n%让小数变为百分数,并保留n位小数

print('{:b}'.format(255))# 11111111
print('{:d}'.format(255))# 255
print('{:o}'.format(255))# 377
print('{:x}'.format(255))# ff
print('{:X}'.format(255))# FF

print('{:.2f}'.format(10))# 10.00
print('{:.0f}'.format(10.11))# 10

print('{:+^20}{:^20}'.format('QAQ','AQA'))# '++++++++QAQ+++++++++        AQA         '
print('{:^>20}{:^<20}'.format('QAQ','AQA'))# '^^^^^^^^^^^^^^^^^QAQAQA^^^^^^^^^^^^^^^^^'

# 这是我们使用较多的一种方法
print('我叫{},我今年{}岁了'.format('张三', 21))# 我叫张三,我今年21岁了

# {数字}会根据数字的顺序进行填入,数字从0开始
print('我叫{1},我今年{0}岁了'.format(21, 'zhangsan'))# 我叫zhangsan,我今年21岁了

# {变量名}
print('我今年{age},我叫{name},我喜欢{sport}'.format(sport='打篮球', name='zhangsan', age=18))
# 我今年18,我叫zhangsan,我喜欢打篮球

# 通过列表索引设置参数
d = ['zhangsan', '18', '湖南', '180']
print('我叫{},我今年{},我来自{},我身高{}'.format(*d))# 我叫zhangsan,我今年18,我来自湖南,我身高180
e = ['hello', 'world']
print("{0[0]} {0[1]}".format(e))# '0'是必须的
# hello world

# 通过字典索引设置参数
# **info对字典进行拆包
# 我觉得应该是变成了('name'='zhangsan','age'= 18,'height'=180,'addr'='湖南')
# 类似于给**kwargs传多个关键字参数一样
info = {'name':'zhangsan','age': 18,'height':180,'addr':'湖南',}
print('大家好我是{name},我今年{age}岁,我来自{addr},我身高{height}'.format(**info))
# 大家好我是zhangsan,我今年18岁,我来自湖南,我身高180

骗赞时间到 快给我点赞


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK