我需要合并字符串以创建一个字符串。例如,需要合并的“hello”字符串为: [H ----],[-E ---],[--LL-]和[---- O]如何在python中合并两个字符串?
这是我必须使字母出现在第一位的当前代码。
display_string = "[" + "".join([x if x == letter else "-" for x in word]) + "]"
我怎么会去制作琴弦如 [H ----],[HE ---],[HELL-],最后[HELLO]?
我需要合并字符串以创建一个字符串。例如,需要合并的“hello”字符串为: [H ----],[-E ---],[--LL-]和[---- O]如何在python中合并两个字符串?
这是我必须使字母出现在第一位的当前代码。
display_string = "[" + "".join([x if x == letter else "-" for x in word]) + "]"
我怎么会去制作琴弦如 [H ----],[HE ---],[HELL-],最后[HELLO]?
我不知道这是否有助于你想要的方式,但这是有效的。问题是我们没有真正的字符串替换。在最后的组装之前,字符列表可能对你更好。
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 + ']'
好吧,所以我想我明白你要去哪里了。
我们定义了一个词“hello”,然后我们遍历“hello”中的所有唯一字母,我们得到您的display_string
s。那么你的问题是如何将它们合并回来?
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))
假设你的字符串列表中的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) + "]"
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)
s = "[H----], [-E---], [--LL-], [----O]"
print(''.join(re.findall(r'\w', s)))
HELLO
你能解释一下'letter'是什么? – bourbaki4481472