简体   繁体   中英

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.

At the moment, it only returns the string + current position of the array. 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

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

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 = 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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