文字列の整列、文字列に不要な内容の削除、印刷文字のフォーマット


文字列に不要な内容を削除
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()関数
''>':右揃え、左揃え'^':中央揃え、左右揃えのデフォルトでもスペース揃えが使用されます.この3つの記号の前に文字を指定して、塗りつぶし文字として使用できます.
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 

:番号の後ろに入力された文字は1文字しかありません.多くなるとエラーが発生します.指定しないとデフォルトはスペースで入力されます.b、d、o、xはそれぞれバイナリ、10進数、8進数、16進数である.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

時間をだまし取る
早くほめてくれ