Skip to content Skip to sidebar Skip to footer

How To Merge Two Strings In Python?

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

Solution 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 + ']'

Solution 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 inrange(0, length):
        for j inrange(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))

Solution 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 inenumerate(single):
        if char != '-': final_string[i]=char

print"[" + ''.join(final_string) + "]"

Solution 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)

Solution 5:

s = "[H----], [-E---], [--LL-],  [----O]"print(''.join(re.findall(r'\w', s)))

HELLO

Post a Comment for "How To Merge Two Strings In Python?"