【问题标题】:Replace spaces with dash and remove prefix from string用破折号替换空格并从字符串中删除前缀
【发布时间】:2011-08-17 05:02:29
【问题描述】:

我正在使用它来删除空格和特殊字符并将字符转换为小写:

''.join(e for e in artistName if e.isalnum()).lower()

我想:

  • -替换空格

  • 如果字符串以单词the开头,那么它

例如,The beatles music! 将变为 beatles-music

【问题讨论】:

    标签: python string replace prefix


    【解决方案1】:
    artistName = artistName.replace(' ', '-').lower()
    if artistName.startswith('the-'):
        artistName = artistName[4:]
    artistName = ''.join(e for e in artistName if e.isalnum() or e == '-')
    

    【讨论】:

    • ...startswith('the-') 会更好;艺术家可能被命名为 theodore ;-)
    【解决方案2】:

    听起来你想制作一个机器可读的 slug。为这个函数使用一个库将为你省去很多麻烦。 python-slugify 做了你想要做的事情,还有很多你可能没想到的事情。

    【讨论】:

      【解决方案3】:

      这最好用一堆正则表达式来完成,这样你就可以随着时间的推移轻松添加。

      不确定 python 语法,但如果是 perl,你会这样做:

      s/^The //g;  #remove leading "The "
      s/\s/-/g;    #replace whitespaces with dashes
      

      看起来 python 有一个很好的正则表达式小方法:http://docs.python.org/howto/regex.html

      【讨论】:

      • 答案应该有一些有效的代码,尤其是正则表达式 b/c,因为它因语言而异。与其说是命令,不如说是正则表达式。
      【解决方案4】:

      Python 3.9开始,也可以使用removeprefix

      'The beatles music'.replace(' ', '-').lower().removeprefix('the-')
      # 'beatles-music'
      

      【讨论】:

        猜你喜欢
        • 2019-09-11
        • 2016-05-09
        • 1970-01-01
        • 2012-12-25
        • 2017-08-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多