Converting List and tuples using str() function

  • #1
402
14

Summary:

I am slightly confused to why using the str() on a tuple and list produces a length greater than a a defined string when comparing lengths

Main Question or Discussion Point

I am currently working my way through some w3schools python exercise on tuples and lists etc and one question was to write a program to converted a tuple to a string.

Now originally I used the str() function on the tuple and printed the result. I then used the string in a for loop for a further question and realized that the tuples and lists were printing additional terms compared when just defining a string using ' '.

As can be seen from my code below

Python:
t =(1,2,3,4,5)
L =[1,2,3,4,5]

string = '1,2,3,4,5'

t = str(t)
L = str(L)

length = len(t)
length1 = len(L)
length2 = len(string)

print(length)
print(length1)
print(length2)
Output
15
15
9

My question why is this, why is there 15 for the list and the tuple yet 9 for the string? Where is the additional six count coming from in the tuple and list?
 

Answers and Replies

  • #2
PeterDonis
Mentor
Insights Author
2019 Award
30,108
9,281
Where is the additional six count coming from in the tuple and list?
Try printing the actual strings you made from the tuple and the list and counting the characters. In other words:

Python:
print(t)
print(L)
 
  • Like
Likes jedishrfu and Taylor_1989
  • #3
402
14
Try printing the actual strings you made from the tuple and the list and counting the characters. In other words:

Python:
print(t)
print(L)
Ah I see the tuple and lists output spaces, thank you.
 
  • Like
Likes jedishrfu
  • #4
PeterDonis
Mentor
Insights Author
2019 Award
30,108
9,281
the tuple and lists output spaces
And the delimiters as well, yes.
 
  • Like
Likes Taylor_1989 and jedishrfu

Related Threads on Converting List and tuples using str() function

Replies
3
Views
581
  • Last Post
Replies
15
Views
673
Replies
3
Views
752
Replies
2
Views
1K
Replies
4
Views
868
Replies
9
Views
715
Replies
9
Views
27K
Replies
1
Views
1K
  • Last Post
Replies
5
Views
13K
Replies
2
Views
2K
Top