書き比べスクリプト・リファレンス

Python

# 文字列の先頭/末尾にある空白文字を削除:strip/lstrip/rstripメソッド
s1 = ' ==** sample text **== '
s2 = s1.strip() # 文字列s1の先頭/末尾にある空白文字を削除
print(s2) # ==** sample text **==

s2 = s1.strip(' =') # 引数に指定した文字を文字列s1の先頭/末尾から削除
print(s2) # ** sample text **

s2 = s1.lstrip(' =*') # 引数に指定した文字を文字列s1の先頭から削除

rstrip

s3 = s1.rstrip(' =*') # 引数に指定した文字を文字列s1の末尾から削除
print('lstrip:', s2) # lstrip: sample text **==
print('rstrip:', s3) # rstrip: ==** sample text

引数を省略した場合、行末の改行文字および空白文字を取り除く

# 特定のプレフィックス/サフィックスを削除:removeprefix/removesuffixメソッド
s1 = '_start_ sample text _end_'
s2 = s1.removeprefix('_start_') # 文字列が'_start_'で始まっていれば、それを削除
print(s2) # sample text _end_

s2 = s1.removesuffix('_end_') # 文字列が'_end_'で終わっていれば、それを削除
print(s2) # _start_ sample text


トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2023-06-28 (水) 22:18:33