【问题标题】:Removing part of string in a python set删除python集中的部分字符串
【发布时间】:2021-03-07 14:48:04
【问题描述】:

从集合中删除字符串的所有部分到并包括点的pythonic方法是什么

theSet={'products.add_product','products.add_category','books.view_books','cats.change_cats'} 

#desired output
newSet = {'add_product','add_category','view_books', 'change_cats'}

【问题讨论】:

  • 我建议浏览str 的文档以找到任何有用的方法。

标签: python string set


【解决方案1】:

试试string.split

{i.split('.')[-1] for i in theSet}
{'add_category', 'add_product', 'change_cats', 'view_books'}

注意:顺序无关紧要,因为它是set

【讨论】:

    【解决方案2】:

    使用str.index()

    data = {'products.add_product', 'products.add_category',
            'books.view_books', 'cats.change_cats'}
    result = {word[word.index(".") + 1:] for word in data}
    
    print(result)
    
    

    Gives :输出顺序可能会有所不同,因为集合是项目的无序集合。

    {'view_books', 'change_cats', 'add_category', 'add_product'}
    

    【讨论】:

      猜你喜欢
      • 2014-02-06
      • 2017-07-02
      • 1970-01-01
      • 1970-01-01
      • 2021-09-04
      • 2020-06-17
      • 2017-02-26
      • 1970-01-01
      相关资源
      最近更新 更多