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

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の先頭から削除
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