'Cant add multiple strings to variable [closed]
I have a problem i am trying to make morse decoder, and want to add two same strings to one variable, but it always add only one but the other disappeared. picture of the code and code can be found below:
print("type something in morse")
choice = input()
choice = choice.replace("/", " ")
times = 0
final = ""
val1 = ""
val2 = ""
val3 = ""
val4 = ""
def stringToList(string):
ListRes = list(string.split("/"))
return ListRes
strA = choice
in_list = stringToList(choice)
long = len(in_list) - 1
for i in range(long):
letter = in_list[times]
if letter == ".-":
val1 = "a"
elif letter == "-...":
val2 = "b"
elif letter == "-.-.":
val3 = "c"
elif letter == "-..":
val4 = "d"
times = times + 1
final = val1 + val2 + val3 + val4
print(final)
Solution 1:[1]
You need to store them as a list of strings, and concatenate each string to the list.
string1 = 'foo'
string2 = 'bar'
strings = []
strings += string1
strings += string2
print(strings)
# ['foo', 'bar']
# use indexing to get each string
print(strings[0])
# 'foo'
print(strings[1])
# 'bar'
Solution 2:[2]
I'm not sure how your program works, there are some parts missing I think. If you want to look up a code, the easiest way is to use a dictionary:
morse = {'.-': 'a',
'-...': 'b',
'-.-.': 'c',
'-..': 'd'} # Complete yourself!}
inp = input("Code: ")
if inp in morse:
print('decoded:', morse[inp])
else:
print('cannot find [', inp, '] in table')
Example run:
Code: -.-.
decoded: c
or
Code: --..
cannot find [ --.. ] in table
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Hunter Boyd |
| Solution 2 |
