anon10023108
anon10023108

Reputation: 141

Parsing a list with hyphens including and extra hyphen at the end

I have a function that takes elements in a list and adds a hyphen between them and it works fine, the issue is when I want to add [" ", " ", " "] as a list it outputs ------ but it should have outputted - - - because there are 3 elements in the list. I can't figure out how to fix this. Any help is appreciated. Thanks in advance.

def printList(myList):

    str1 = ' '.join(map(str,myList))
    
    for i in range(0, len(str1), 1):
        if (str1[i] == ' '):
            str1 = str1.replace(str1[i], '-')
    print(str1 + "-")
printList([" ", " ", " "])

Upvotes: 0

Views: 334

Answers (1)

PacketLoss
PacketLoss

Reputation: 5746

You should use join() as this is exactly what it is designed for.

'-'.join([" ", " ", " "])
#' - - '

If you also want to add - to the end, just add it to the output string

'-'.join([" ", " ", " "]) + '- '
#' - - - '

For integer based lists, map your elements to str()

'-'.join(map(str, [1, 2, 3, 4, 5]))
#'1-2-3-4-5'

Upvotes: 3

Related Questions