【问题标题】:How to merge two strings in python?如何在python中合并两个字符串?
【发布时间】:2015-10-14 23:10:18
【问题描述】:

我需要将字符串合并在一起以创建一个字符串。例如,需要组合的“hello”字符串是: [H----]、[-E---]、[--LL-] 和 [----O]

这是我必须让字母首先出现的当前代码。

display_string = "[" + "".join([x if x == letter else "-" for x in word]) + "]"

我将如何制作字符串,例如 [H----]、[HE---]、[HELL-],最后是[HELLO]?

【问题讨论】:

  • 你能解释一下letter是什么吗?

标签: python string concatenation


【解决方案1】:

我不知道这是否有助于您想要的方式,但这有效。问题是我们并没有真正的字符串替换。在最终组装之前,字符列表可能更适合您。

string_list = [
    'H----',
    '-E---',
    '--LL-',
    '----O'
]

word_len = len(string_list[0])
display_string = word_len*'-'
for word in string_list:
    for i in range(word_len):
        if word[i].isalpha():
            display_string = display_string[:i] + word[i] + display_string[i+1:]
    print '[' + display_string + ']'

【讨论】:

    【解决方案2】:

    好的,所以我想我知道你打算用这个做什么了。

    我们定义一个像“hello”这样的词,然后我们遍历“hello”中的所有唯一字母,我们得到你的display_strings。那么您的问题是如何将它们重新合并在一起?

    word = "HELLO"
    all_display_strings = ["[" + "".join([x if x == letter else "-" for x in word]) + "]" for letter in word]
    # now merge the list of lists
    length = len(all_display_strings[0])-2 # -2 for the opening and closing bracket
    merged_display_strings = ['-']*length
    
    for i in range(0, length):
            for j in range(0, len(all_display_strings)):
                if (all_display_strings[j][i+1] != '-'):
                    merged_display_strings[i] = all_display_strings[j][i+1]
    
    
    print(''.join(merged_display_strings))
    

    【讨论】:

      【解决方案3】:

      假设您的字符串在列表中 all_strings

      all_strings = ["[H----]", "[-E---]", "[--LL-]", "[----O]"]
      # clean them
      all_strings = map(lambda x:x.strip()[1:-1], all_strings)
      
      # Let's create a list for the characters in the final string(for easy mutating)
      final_string = ['' for _ in xrange(max(map(len, all_strings)))]
      
      for single in all_strings:
          for i, char in enumerate(single):
              if char != '-': final_string[i]=char
      
      print "[" + ''.join(final_string) + "]"
      

      【讨论】:

        【解决方案4】:
        strings = 'h----', '-e---', '--ll-', '----o'
        letterSoups = [ [ (p, c) for (p, c) in enumerate(s) if c != '-' ]
            for s in strings ]
        result = list('-----')
        for soup in letterSoups:
          for p, c in soup:
            result[p] = c
        print ''.join(result)
        

        【讨论】:

          【解决方案5】:
          s = "[H----], [-E---], [--LL-],  [----O]"
          
          print(''.join(re.findall(r'\w', s)))
          
          HELLO
          

          【讨论】:

            猜你喜欢
            • 2015-09-01
            • 1970-01-01
            • 2017-08-12
            • 2019-06-29
            • 1970-01-01
            • 2017-10-25
            • 2018-02-14
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多