【问题标题】:How to strip a string with a "." properly in Python? [duplicate]如何用“。”剥离字符串在Python中正确吗? [复制]
【发布时间】:2018-11-04 21:01:57
【问题描述】:

我想去掉字符串的结尾,如下所示:

da = "abc.com"
print(da.strip(".com"))

我的预期结果是abc。但是,会返回 ab

为什么会这样以及如何解决?

【问题讨论】:

  • 你试过da.replace('.com','')吗?由于 strip 从字符串中清除了 '.com' 中包含的所有单个字符。
  • 这是因为c 也包含在.com 中,请使用replace()split()regex
  • 问题是由于给strip 的参数是要删除的字符列表。所以你是说:删除每一个'.',每一个'c',每一个'o',每一个'm。

标签: python python-3.x substring strip


【解决方案1】:

这应该可行:只需将字符串按. 拆分并丢弃最后一段。

print(da.split('.')[:-1])

【讨论】:

  • 这适用于提供的示例,但会破坏其他 url,如“some.thing.abc.com”。
  • @meissner_ 对。添加了通用解决方案。
【解决方案2】:

使用正则表达式。

import re
da = "abc.com"
print(re.sub("\.com", "", da))

print(da.replace(".com", ""))

输出:

abc

【讨论】:

    猜你喜欢
    • 2021-08-12
    • 1970-01-01
    • 2018-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多