【问题标题】:Split user input string into a list with every character将用户输入字符串拆分为每个字符的列表
【发布时间】:2020-06-21 09:04:53
【问题描述】:

我正在尝试为 micro:bit 编写一个程序,它将文本显示为莫尔斯电码。我查看了多个网站和 Stack Overflow 帖子,寻找一种将字符串拆分为字符的方法。

例如 string = "hello"chars = ["h","e","l","l","o"]

我尝试创建一个名为 array 的函数来执行此操作,但这不起作用。

然后我尝试了这个:

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

有什么想法吗?

【问题讨论】:

  • list("hello") == ['h', 'e', 'l', 'l', 'o'].
  • 这将如何运作?
  • 在 ipython 控制台中尝试 list('hello')..
  • 在普通 IDLE 下也能正常工作。

标签: python micropython text-segmentation bbc-microbit


【解决方案1】:

您可以使用内置的 list() 函数:

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

在您的情况下,您可以调用 list(getMessage()) 将文件的内容转换为字符。

【讨论】:

  • list 采用任意可迭代值,并创建一个列表,其中可迭代的每个元素作为单独的列表项。作为一个可迭代对象,str 被认为是由一系列单字符字符串组成的。
【解决方案2】:

你可以试试这样的:

word="你好"

结果 = [] 结果[:0] = 单词

打印(结果)

现在结果将是 ['h', 'e', 'l', 'l', 'o']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-01
    • 2011-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多