1

I'm trying to write a program for the micro:bit which displays text as morse code. I've looked at multiple websites and Stack Overflow posts for a way to split a string into characters.

E.g. string = "hello" to chars = ["h","e","l","l","o"]

I tried creating a function called array, to do this, but this didn't work.

I then tried this:

def getMessage():
    file = open("file.txt", "r")
    data = file.readlines() 
    file.close()
    words = []
    for line in data:
        for word in line:
            words.append(word)
    return words

Any ideas?

edapm
  • 45
  • 1
  • 9

2 Answers2

2

You can use builtin list() function:

>>> list("A string") 
['A', ' ', 's', 't', 'r', 'i', 'n', 'g'] 

In your case, you can call list(getMessage()) to convert the contents of the file to chars.

shargors
  • 2,147
  • 1
  • 15
  • 21
  • 2
    `list` takes an arbitrary iterable value, and creates a list with each element of the iterable as separate list item. As an iterable, a `str` is considered to be made up of a sequence of one-character strings. – chepner Mar 09 '20 at 13:13
-2

You can try something like this:

word="hello"

result = [] result[:0] = word

print(result)

Now result will be ['h', 'e', 'l', 'l', 'o']