简体   繁体   English

Python 循环和 Append 到字符串

[英]Python Loop and Append to String

I have a string field and an array of numbers.我有一个字符串字段和一个数字数组。 When I iterate through the list I should get the string to append with the number from the array.当我遍历列表时,我应该使用数组中的数字获取到 append 的字符串。

At the moment, it only returns the string + current position of the array.目前,它只返回数组的字符串+当前position。 The following is my code.以下是我的代码。 How could I solve this?我怎么能解决这个问题?

digit_list = list(map(int, str(extra_digits)))
pi_local = "PI"
for digit in range(len(digit_list)):
    pi_local = pi_local + str(digit_list[counter])
    pi_label.config(text = pi_local)

initial incorrect output初始不正确 output

I have tried the suggestion below by trying to iterate over the list, but I am still not getting the right result.我通过尝试迭代列表尝试了以下建议,但我仍然没有得到正确的结果。 full code is below完整代码如下

pi = "PI"
extra_digits = "159265358979323846"


counter = 0
init = 2

#digit_list = list(map(int, str(extra_digits)))



def button_pressed():
    global counter
    global pi
    #global digit_list
    global init
    digit_list = list(map(int, str(extra_digits)))
    our_label.config(text="Pi to " + str(init+counter) + " decimals")
    pi_local = pi
    for digit in digit_list:
        pi_local = pi_local + str(digit)
        pi_label.config(text = str(digit))
        #pi_label.config(text = str(pi) + str(digit_list[counter]))
    counter = counter +  1

The output I am getting is Current incorrect output after using solution below使用以下解决方案后,我得到的 output 电流不正确 output

In [77]: pi_local = "PI"                                                                                                                                                                                    

In [78]: digit_list = [1,3,5,2]                                                                                                                                                                             

In [79]: [str(i) + pi_local for i in digit_list]                                                                                                                                                            
Out[79]: ['1PI', '3PI', '5PI', '2PI']

You need to iterate through the elements in digit_list您需要遍历digit_list中的元素

digit_list = list(map(int, str(extra_digits)))
pi_local = "PI"
for digit in digit_list:
    pi_local = pi_local + str(digit)
    pi_label.config(text = pi_local)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM