LoginSignup
1
2

More than 3 years have passed since last update.

【python】 末尾の特定の文字列を削除

Last updated at Posted at 2020-07-13

末尾にある特定の文字列を削除したいとき

ある文字列Sに対し、Sの末尾にsという文字列があった場合、
末尾のsだけ削除する、というとき。

S = 'abc123abcabc'
s = 'abc'

if S.endswith(s):
    S = S[:-len(s)]
print(S)  

# 出力結果: abc123abc

また、正規表現を用いて同様のことができます。

import re

S = "abc123abcabc"
s = "abc$"

print(re.sub(search, "", string))

# 出力結果: abc123abc

こちらのほうがすっきりしていいかもしれません。


最初、rstrip()を使う方法も書いていましたが、
完全に勘違いしていたので、削除しました。
コメントありがとうございました。

1
2
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2