尝试制作一个 Raspberry Pi Pico 项目,用摩尔斯电码闪烁一盏灯。我如何从 "word" 变量中获取单独的字符?

Trying to make a Raspberry Pi Pico project that blinks a light in morse code. How would I get the separate character from the "word" variable?

from machine import Pin
from time import sleep
led = Pin(0, Pin.OUT)


def dot():
    led.value(1)
    sleep(0.5)
    led.value(0)
    sleep(2)


def dash():
    led.value(1)
    sleep(1)
    led.value(0)
    sleep(2)


# 0.5 Seconds = Dot
# 1 Second = Dash

# word to be translated
word = "Hi"

您可以将 Python 中的字符串视为列表,例如:

word = "Hi"
print(word[0])
print(word[1])
#H
#i

了解这一点,您可以迭代一个字符串:

word = "Hi"
for letter in word:
   print(letter)

#H
#i

对于你的问题,你也可以将所有字母映射到各自的代码:


# 0 -> dot
# 1 -> dash
codes = {
   "A": (0, 1),
   "B": (1, 0, 0, 0),
   "C": (1, 0, 1, 0)
}

word = "AC"

for letter in word:
    morse_codes = codes[letter]
    print(morse_codes)
}
#(0, 1)
#(1, 0, 1, 0)