How to merge two strings in python?

不打扰是莪最后的温柔 提交于 2019-12-13 09:13:16

问题


I need to merge strings together to create one string. For example the strings for "hello" that need to be combined are: [H----], [-E---], [--LL-], and [----O]

This is the current code I have to make the letters appear in the first place.

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

How would I go about making strings such as [H----], [HE---], [HELL-], and finally [HELLO]?


回答1:


I don't know whether this helps in the way you wanted, but this works. The problem is that we don't really have a string replacement. A list of chars might work better for you until the final assembly.

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:


Okay so I think I see where you are going with this.

We define a word like "hello," then we iterate over all unique letters in "hello" and we get your display_strings. Then your question is about how to merge them back together?

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:


Assuming your strings are in a list 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


来源:https://stackoverflow.com/questions/33137198/how-to-merge-two-strings-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!