刪除字符串中不需要的內(nèi)容
1、strip()方法
strip:默認(rèn)是去掉首尾的空白字符,但是也可以指定其他字符;
lstrip:只去掉左邊的;
rstrip:只去掉右邊的;
print('+++apple '.strip()) # '+++apple'
print('+++apple '.lstrip('+')) # 'apple '
print(' apple '.rstrip()) # ' apple'
這個(gè)只能去除首尾的,如果想去除中間的字符,可以使用倒replace()方法
2、replace()方法
replace:將字符串中所有需要替換的字符替換成指定的內(nèi)容,如果指定次數(shù)count,則替換不會(huì)超過count次;原來的字符串不會(huì)改變,而是生成一個(gè)新的字符串來保存替換后的結(jié)果。
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
字符串對(duì)齊
ljust(width,fillchar) :返回一個(gè)左對(duì)齊的長度為width的字符串,要是字符串長度小于width則在右邊用所給填充字符補(bǔ)齊
rjust(width,fillchar) :右對(duì)齊,同上
center(width,fillchar):居中,同上
print('hello'.ljust(10, '+'))# hello+++++
print('hello'.rjust(10))# ' hello'
print('hello'.center(10, '='))# ==hello===
format()函數(shù)
‘':左對(duì)齊,右補(bǔ)齊
‘>':右對(duì)齊,左補(bǔ)齊
‘^':居中,左右補(bǔ)齊
默認(rèn)也是使用空格補(bǔ)齊,可以在這三個(gè)符號(hào)前給定字符,作為填充字符
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歲
: 號(hào)后面帶填充的字符,只能是一個(gè)字符,多了會(huì)報(bào)錯(cuò),不指定的話默認(rèn)是用空格填充;
b、d、o、x 分別是二進(jìn)制、十進(jìn)制、八進(jìn)制、十六進(jìn)制;
.nf保留n位小數(shù)
.n%讓小數(shù)變?yōu)榘俜謹(jǐn)?shù),并保留n位小數(shù)
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歲了
# {數(shù)字}會(huì)根據(jù)數(shù)字的順序進(jìn)行填入,數(shù)字從0開始
print('我叫{1},我今年{0}歲了'.format(21, 'zhangsan'))# 我叫zhangsan,我今年21歲了
# {變量名}
print('我今年{age},我叫{name},我喜歡{sport}'.format(sport='打籃球', name='zhangsan', age=18))
# 我今年18,我叫zhangsan,我喜歡打籃球
# 通過列表索引設(shè)置參數(shù)
d = ['zhangsan', '18', '湖南', '180']
print('我叫{},我今年{},我來自{},我身高{}'.format(*d))# 我叫zhangsan,我今年18,我來自湖南,我身高180
e = ['hello', 'world']
print("{0[0]} {0[1]}".format(e))# '0'是必須的
# hello world
# 通過字典索引設(shè)置參數(shù)
# **info對(duì)字典進(jìn)行拆包
# 我覺得應(yīng)該是變成了('name'='zhangsan','age'= 18,'height'=180,'addr'='湖南')
# 類似于給**kwargs傳多個(gè)關(guān)鍵字參數(shù)一樣
info = {'name':'zhangsan','age': 18,'height':180,'addr':'湖南',}
print('大家好我是{name},我今年{age}歲,我來自{addr},我身高{height}'.format(**info))
# 大家好我是zhangsan,我今年18歲,我來自湖南,我身高180
總結(jié)
到此這篇關(guān)于Python字符串對(duì)齊、刪除字符串不需要的內(nèi)容以及格式化打印字符的文章就介紹到這了,更多相關(guān)Python字符串對(duì)齊、刪除及格式化打印內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- Python如何對(duì)齊字符串
- 解決Python對(duì)齊文本字符串問題
- Python中字符串對(duì)齊方法介紹
- Python字符串對(duì)齊方法使用(ljust()、rjust()和center())