・文字列を置き換える .replace()
.replace( 'old', 'new' ) で文字列の一部を差し替えられる。同じ文字があれば全て置き換えられる。
strA = 'abcdefg'
print( strA )
print( strA.replace( 'def', '@@@' ) )
strB = 'ab-cd-ef-gh'
print( strB )
print( strB.replace('-', '@' ) )
#出力
# abcdefg
# abc@@@g
# ab-cd-ef-gh
# ab@cd@ef@gh
・文字列を置き換える .format()
.format() で指定した文字で、文字列内の {} を差し替えられる。{} が複数ある場合は、 , で区切り {} の数だけ文字を指定する。
strC = 'abc{}def'
print( strC )
print( strC.format( '@@@' ) )
strD = 'abc{}def{}ghi'
print( strD )
print( strD.format( '@@@', '---' ) )
print( strD.format( '@@@' ) ) #これはエラーになる
#出力
# abc{}def
# abc@@@def
# abc{}def{}ghi
# abc@@@def---ghi
# IndexError: tuple index out of range
{} に番号を指定して区別することができる。(0始まり)
番号の数だけ文字を指定する。
strE = 'abc{0}def{1}ghi{2}jkl{1}'
print( strE )
print( strE.format( '@@@', '---', '===' ) )
print( strE.format( '@@@', '---' ) ) #これはエラーになる
#出力
# abc{0}def{1}ghi{2}jkl{1}
# abc@@@def---ghi===jkl---
# IndexError: tuple index out of range
・文字列を分割する
.split() で指定した文字で文字列を分割したリストを作成できる。
strA = 'abcdefg'
print( strA )
print( strA.split('d') )
strB = 'ab-cd-ef-gh'
print( strB )
print( strB.split('-') )
print( strB.split('-')[2] )
#出力
# abcdefg
# ['abc', 'efg']
# ab-cd-ef-gh
# ['ab', 'cd', 'ef', 'gh']
# ef
0 件のコメント:
コメントを投稿