【问题标题】:Changing letters for uppercased in a given string - Python更改给定字符串中的大写字母 - Python
【发布时间】:2021-08-16 15:53:27
【问题描述】:

我正在尝试编写一个函数,该函数将创建一个基于相同单词但不同字母大写的字符串列表。目前我有这样的事情:

word = 'passwordPASSWORD'

def generator():
    list_ = []
    result = itertools.permutations(word, (len(word)//2)))
    for el in result:
        x = ''.join(list(map(lambda x: x.lower(), el)))
        if x == 'password':
            list_.append(''.join(el))
    return list_

generator() 

因此我需要(例如,它会很短)list_ = [password, pAssword, PaSSwORd,passWORD, ......等] 我尝试过使用 itertools.permutation 但对于更长的单词(如密码),脚本无法完成迭代。

提前感谢您对此问题的任何支持。

【问题讨论】:

    标签: python python-3.x string iteration


    【解决方案1】:

    这里使用来自itertoolsproduct

    from itertools import product
    
    word = 'password'
    
    [''.join(x) for x in product(
        *[[l.upper(), l.lower()] for l in word])]
    

    输出:

    ['PASSWORD',
     'PASSWORd',
     'PASSWOrD',
     'PASSWOrd',
     'PASSWoRD',
     'PASSWoRd',
     'PASSWorD',
     'PASSWord',
     'PASSwORD',
     'PASSwORd',
     'PASSwOrD',
     'PASSwOrd',
     'PASSwoRD',
     'PASSwoRd',
     'PASSworD',
    ...
    

    【讨论】:

      【解决方案2】:

      试试这个功能:

      def all_casings(input_string):
          if not input_string:
              yield ""
          else:
              first = input_string[:1]
              if first.lower() == first.upper():
                  for sub_casing in all_casings(input_string[1:]):
                      yield first + sub_casing
              else:
                  for sub_casing in all_casings(input_string[1:]):
                      yield first.lower() + sub_casing
                      yield first.upper() + sub_casing
      

      然后这样称呼它:

      [x for x in all_casings("foo")]
      

      【讨论】:

        猜你喜欢
        • 2017-10-09
        • 2023-03-09
        • 2011-05-12
        • 2012-01-03
        • 2021-08-13
        • 1970-01-01
        • 2013-08-10
        • 2021-01-06
        • 1970-01-01
        相关资源
        最近更新 更多