Why is the first word [] output when converting a python list into a str function?

Asked 2 years ago, Updated 2 years ago, 14 views

Hello, I am an ordinary person who learns programming as a hobby. I have a few questions for you.

a = 1
b = 2
result = []
result_max = []

while a <= 10: # a <= 15:2 to 15 wins.
    result.append(b)
    b = b * 2   
    a = a + 1

print(result)
max_result = max(result)
result_max.append(max_result)
print(result_max)

result_max_str = str(result_max)
print(result_max_str[0])

the resultant value of [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] [1024] [

That's it. The last... From the result of print(result_max_str[0]). Why does the list come up?

What should I do to prevent this from happening?

python

2022-09-21 19:15

3 Answers

Younghoon explained it well. If you want to print the list [1,2,3,4,5] without a square bracket ([or ]), refer to the following code.

a = [1,2,3,4,5]
print(*a) # 1 2 3 4 5 Output
print (*a, step = ',') # 1, 2, 3, 4, 5 outputs


2022-09-21 19:15

First, when str = 'abcd' , str[0] is a.

result_max_str = str(result_max) #result_max is a list with 1024. Transform to string and save result_max_str as "[1024]"
print(result_max_str[0]) # [Output] for index 0

The list itself is stored as a string by performing a type conversion and outputting the 0th value of the string, resulting in [].

If you want to print out 1024,

print(result_max[0])

You can do it.


2022-09-21 19:15

If you really want to convert it to string...

result_max_str = str(result_max[0])
print(result_max_str)


2022-09-21 19:15

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.