2

please be aware, im new to python: i'm trying to create a defined function that can convert a list into a string, and allows me to put a separator in. The separator has to be ', '. My current thought process is to add each item from a list to an empty string variable, and then I'm trying to make use of the range function to add a separator in. I'm only wanting to use str() and range().

def list2Str(lisConv, sep = ', '):
    var = ''
    for i in lisConv:
        var = var + str(i)
        #test line
        print(var, "test line")
    var1 = int(var)
    for a in range(var1):
        print(str(var1)[a],  sep = ', ')

list1 = [2,0,1,6]        

result = list2Str(list1, ', ')
print(result)

3 Answers3

5

First you need to convert the list of int to a list of string.

You can use list comprehension : https://docs.python.org/3/tutorial/datastructures.html

str_list = [str(x) for x in list1]

Then, join the list of string with the separator you want.

sep = ', '
print(sep.join(str_list))

In a more concise way:

print(', '.join([str(x) for x in [1, 2, 3]))

More information about join here: http://www.diveintopython.net/native_data_types/joining_lists.html

SnoozeTime
  • 363
  • 1
  • 9
  • 1
    Or even more concise: `sep.join(map(str, the_list))` – dawg Jun 03 '16 at 01:44
  • Yep, map function is great but i heard it is advised to use list comprehension instead =) http://stackoverflow.com/questions/1247486/python-list-comprehension-vs-map – SnoozeTime Jun 03 '16 at 01:45
1
list=['asdf', '123', 'more items...']
print ', '.join([str(x) for x in list])

If you wanted to create your own function to convert you could do the following.

def convert(list, sep):
    n_str = ''
    for index, I in enumerate(list): #enumerate(list) returns (current position, list[current position]) so if we need to know the current position we use enumerate
        if index != len(list)-1:
            n_str += str(i) + sep #we don't apply the seperator if we're at the end of the list
        else:
            n_str += str(i)
    return n_str
TheLazyScripter
  • 2,541
  • 1
  • 10
  • 19
  • what if the items in the list aren't strings? – tom10 Jun 03 '16 at 01:42
  • the list i'm looking to manipulate is not necessarily a string which is why i've included code to try and create a string, and then want to include the separator. FYI this is for homework, and we're not allowed to use string methods – Newerino6525 Jun 03 '16 at 01:49
  • Ok. The post was already edited to include a function that converts a list to a string, separating each item in the list with a sep. – TheLazyScripter Jun 03 '16 at 01:51
  • that second explanation is more what i was looking for :) in regards to my code (for learning purposes) is it that the code is over the top and trying to do too much and wasn't kept simple? – Newerino6525 Jun 03 '16 at 01:53
  • The reason I rewrote your function is because it was trying to do too much (i.e. your debugging statements and variables were cluttering the function) if you wanted to print the result you could `print(convert(list, ', '))` – TheLazyScripter Jun 03 '16 at 01:55
  • i guess keeping it simple is always the thing to remember when learning coding. don't try to do too much. – Newerino6525 Jun 03 '16 at 01:58
  • Exactly, simpler is often, but not always, faster and easier to read. Good Luck! – TheLazyScripter Jun 03 '16 at 02:00
  • Just a query in regards to the convert function here, is there a way that I can remove the trailing separator? e.g. output may be object1, object2, but I don't want the , after object 2? I want it to appear as object1, object2 – Newerino6525 Jun 08 '16 at 09:50
  • @Newerino6525 sure, I have updated the answer to reflect this change! – TheLazyScripter Jun 08 '16 at 15:14
0

If no string methods (like join) are allowed, reduce should offer the shortest solution:

def list2Str(lisConv, sep = ', '):
    return reduce(lambda x, y: str(x) + sep + str(y), lisConv)

print(list2Str([2, 0, 1, 6], ', '))
# 2, 0, 1, 6
user2390182
  • 72,016
  • 6
  • 67
  • 89