【问题标题】:string list members in sample string in PythonPython中示例字符串中的字符串列表成员
【发布时间】:2014-12-27 17:19:17
【问题描述】:

我有一个要检查的字符串列表是否不在非列表字符串中。例如,说我有

myString = 'zyxwvutsr'

l = ['abc', 'def']

我想遍历l 的成员并检查这些不是myString 的子字符串,并且仅当在源字符串中找到abcdef 时才退出检查循环。

感觉应该能写出类似的东西

while s for s in l not in myString:
    myString += random character

【问题讨论】:

    标签: python string list iteration


    【解决方案1】:

    下面的代码将向字符串添加随机字母,直到 l 中包含的字符串在您的字符串中。

    它使用string.ascii_lowercase 获取字母a-zrandom.choice 以从该字符串中选择一个随机字符添加到s

    while 循环使用all 来检查l 中包含的所有子字符串是否在s 中。

    import random
    import string
    
    lower = string.ascii_lowercase # letters a-z
    
    s = 'zyxwvutsr'
    
    l = ['abc', 'def']
    
    # This loop will continue while the string s does not
    # contain all of the substrings in l
    while not all(i in s for i in l):
        s += random.choice(lower)
    

    【讨论】:

      【解决方案2】:

      这行得通

      myString = 'zyxwvutsr'
      
      l = ['abc', 'def', 'wvu']
      
      
      for word in l:
          if word in myString:
             print(word)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-28
        • 1970-01-01
        相关资源
        最近更新 更多