You need if to skip separator before first char
def to_string(my_list, sep=', '):
string = ''
for char in my_list:
if string: # if string is not empty then add separator
string = string + sep
string = string + char
return string
my_list = ['H','E','L','p']
print(to_string(my_list, '-'))
Other method is to get first char and always add separator. But it needs to check if list is not empty.
def to_string(my_list, sep=', '):
if not my_list:
return ''
string = my_list[0]
for char in my_list[1:]:
string = string + sep + char
return string
my_list = ['H','E','L','p']
print(to_string(my_list, '-'))
Answer from furas on Stack OverflowConverting list to string
python - How to convert list to string - Stack Overflow
convert list thats a string back to a list?
Python AI game: convert list of lists and string to set
You need if to skip separator before first char
def to_string(my_list, sep=', '):
string = ''
for char in my_list:
if string: # if string is not empty then add separator
string = string + sep
string = string + char
return string
my_list = ['H','E','L','p']
print(to_string(my_list, '-'))
Other method is to get first char and always add separator. But it needs to check if list is not empty.
def to_string(my_list, sep=', '):
if not my_list:
return ''
string = my_list[0]
for char in my_list[1:]:
string = string + sep + char
return string
my_list = ['H','E','L','p']
print(to_string(my_list, '-'))
you can just do as below
def to_string(my_list, sep=', '):
return sep.join(my_list)
my_list = ['H','E','L','p']
to_string(my_list, "-")
Hi 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