prp
prp

Reputation: 962

Python. Why the length of the list changes after turning it from int to string?

I have a bunch of users in a list called UserList. And I do not want the output to have the square brackets, so I run this line:

UserList = [1,2,3,4...]
UserListNoBrackets = str(UserList).strip('[]')

But if I run:

len(UserList) #prints22 (which is correct).

However:

len(UserListNoBrackets) #prints 170 (whaaat?!)

Anyway, the output is actually correct (I'm pretty sure). Just wondering why that happens.

Upvotes: 2

Views: 76

Answers (2)

bruno desthuilliers
bruno desthuilliers

Reputation: 77902

Here:

UserListNoBrackets = str(UserList).strip('[]')

UserListNoBrackets is a string. A string is a sequence of characters, and len(str) returns the numbers of characters in the string. A comma is a character, a white space is a character, and the string represention of an integer has has many characters as there are digits in the integer. So obviously, the length of your UserListNoBrackets string is much greater than the length of you UserList list.

Upvotes: 2

Rakesh
Rakesh

Reputation: 82765

You probably need str.join

Ex:

user_list = [1,2,3,4...]
print(",".join(map(str, user_list)))

Note: Using map method to convert all int elements in list to string.

Upvotes: 2

Related Questions