以下のようなコードがあります。
url = 'abcdc.com' print(url.strip('.com'))
I expected: abcdc.
abcdc
私が得たのはabcd です。
abcd
ここで、私は
url.rsplit('.com', 1)
他に良い方法はありますか?
stripは "remove this substring" という意味ではありません。x.strip(y)は、yを文字の集合として扱い、その集合の中の任意の文字をxの両端から取り除きます。
は "remove this substring" という意味ではありません。x.strip(y)
y
x
代わりに、endswithとスライスを使うことができます。
endswith
url = 'abcdc.com' if url.endswith('.com'): url = url[:-4]
または、正規表現を使う。
import re url = 'abcdc.com' url = re.sub('\.com$', '', url)
url[:-4]`はどうでしょうか?
これは、正規表現の完璧な使い方です。
>>> import re >>> re.match(r"(.*)\.com", "hello.com").group(1) 'hello'
strip
は "remove this substring" という意味ではありません。x.strip(y)
は、y
を文字の集合として扱い、その集合の中の任意の文字をx
の両端から取り除きます。代わりに、
endswith
とスライスを使うことができます。または、正規表現を使う。
url[:-4]`はどうでしょうか?
これは、正規表現の完璧な使い方です。