+ 2

Convert list into a string

How to convert list to string? + As I know, we can convert it using join() method after we create list like list_string = ['a', 'b', 'c'] then convert it with ' '.join(list_string) and it will return abc right? But that's a bit weird using .join() method to convert list into a string. + And also as far as I know we can also use *args , like print(*li) then you will get a b with a space. But it only works if inside the print() function. Is there any other way besides using the two methods above? to convert list to string? Please!n!... helpme.....!!!

31st Jan 2025, 1:25 PM
Kapi
Kapi - avatar
5 Answers
+ 1
You can use a string builder and loop through the list: string = "" characters = ["a", "b", "c"] for item in characters: string += str(characters) #This ensures that any item in the list will be converted to a string #... Is it what you're looking for?
31st Jan 2025, 1:46 PM
Dragon RB
Dragon RB - avatar
0
Nooo... I mean I want to convert list : characters = ["a", "b", "c"] into "abc" and has a string type in it. Not what is in the list is converted to string. Here lemme sho u : https://sololearn.com/compiler-playground/cJCzOp88EdYq/?ref=app there the string variable has a string type right? which initially has a list type/class
31st Jan 2025, 2:38 PM
Kapi
Kapi - avatar
0
Kapi For whatever reason, the developers of Python decided that using str() on a list would generate a string representation of the list instead of concatenating the elements of the list. EXAMPLE li = ["a", "b", "c"] st = str(li) # st = "[a, b, c]" # NOT st = "abc" So to actually concatenate all list elements into a string, you must either use join() or loop over list elements and concatenate yourself EXAMPLE st1 = "".join(li) OR st2 ="" for item in li: st2 += item
31st Jan 2025, 4:24 PM
Shardis Wolfe
0
I came up with these ways to use the extraction operator to build a string while avoiding join(). No loops, either. Though I suspect that if you are unsatisfied with using join() then these will be less appealing. https://sololearn.com/compiler-playground/c81VioYYDdox/?ref=app
31st Jan 2025, 5:56 PM
Brian
Brian - avatar
0
Brian I also came up with a solution, which uses reduce() function from the functools library: https://sololearn.com/compiler-playground/cfEY8DHEjkq3/?ref=app I'm not sure if it also counts, though.
31st Jan 2025, 6:46 PM
Dragon RB
Dragon RB - avatar