Use ''.join:
xs = ['1', '2', '3']
s = ''.join(xs)
If the list contains integers, convert the elements to string before joining them:
xs = [1, 2, 3]
s = ''.join(str(x) for x in xs)
Answer from Senthil Kumaran on Stack OverflowHi everyone, I just wanted to know what is the best way to convert an entire list to a simple string element. I was trying out stuff I learned by coding a (very) simple password generator and I am stuck at figuring out how to output the password as a single string (without the empty spaces and brackets) instead of getting the entire array.
My code :
import string
import random
letters = list(string.ascii_lowercase)
#Generates a random password with default value of 3 numbers and 3 letters (x and y arguments)
def password_gen(x=3, y=3):
char_list = []
#Returns a random letter
def add_letter() :
return random.choice(letters)
#Returns a random number (0-9)
def add_number() :
return int(random.random()*10)
#Loops to add the correct number of random characters
i = 0
while i < x :
char_list.append(add_letter())
i+=1
i=0
while i < y :
char_list.append(add_number())
i+=1
#Shuffles the list and returns it as the generated password
random.shuffle(char_list)
return char_list
password = str(password_gen(5, 5))
print(password)
Currently the output gives something looking like this : ['p', 3, 5, 9, 'o', 'v', 'a', 9, 't', 3] and I want it to look like this p359ova9t3
Hopefully I can explain this properly. I have no control over how the input string which is kind of formatted like a list of lists but without quotes (so I can't use json.loads)
Example input (I'm reading it in using sys.argv):
"[[a,1],[b,2]]"
I'd like to convert this to be a real list of lists so I can iterate through them in my script.
I can get what I need using split but I was wondering if there was a better way to do it. Either a better way to divide them or a way to add quotes - whatever works.
import sys
try1 = sys.argv[1]
lst1 = try1.split("],")
print("try #1 (works but could be better?)")
print(len(lst1))
for item in lst1:
print(item.lstrip("[[").rstrip("]]"))
# doesn't work - 1 item in the list
print("\n\nTry #2")
try2 = sys.argv[1:]
print(len(try2))
# doesn't work - length of 13
print("\n\nTry #3")
print(len(list(sys.argv[1])))Output
$ python3 t.py "[[a,1],[b,2]]" try #1 (works but could be better?) 2 a,1 b,2 Try #2 1 Try #3 13
Thanks for reading