0

我正在通过机器人框架传递一个参数。参数是一个字符串。“底特律”。我希望代码将该字符串分解为“D”、“De”、“Det”、“Detr”、“Detro”、“Detroi”和“Detroit”。当然,如果输入另一个字符串,比如“Flint”,它只会将其分解为 5 个元素。F、Fl、Fli、Flin、Flint。

(伪代码)

def checkCity (self, x):
     (take x which is the string, and make it a list of elements containing the letters as above).
     (Then take each element and check it against data provided by the device(using a loop for each iteration)
     (Once any of the elements are matched to the data, return another function that acts as a key press)

我对python(和编程)足够熟悉,一般都有理论,只是不知道如何编码。

4

2 回答 2

0

在 python 中,您可以通过使用访问字符串的各个部分

string[5:7]

这将给出第 5 个和第 6 个字符

python中的这个函数将返回一个你想要的列表

def toSubLists(string):
    sublists = []
    for i in range(1, len(string)+1):
        sublists.append(string[0:i])
    return sublists
于 2013-11-30T13:58:01.757 回答
0

我不熟悉您使用的编程语言,但我会尽我所能提供帮助。

为了分解字符串,您可以使用while循环或for循环,无论您喜欢哪个。结束条件是您放入第二个参数的字符串的长度。在循环中,您可以使用substring方法分解字符串并将每个元素存储到数组列表中。

然后为了检查是否有任何元素匹配,您将(如您所说)为每次迭代使用一个循环。

于 2012-06-21T13:32:15.853 回答