0
def display(xs):
    string1 = ''
    for i in range(len(xs)):
        string1+=str(xs[i])+'-'
    return string1

Given a list of tuples as xs = [(2,3),(4,4),(5,5),(6,6)].Return this list as a string, by adding them up with dashes '-'.

So I wan to return a string that looks something like '(2,3)-(4,4)-(5,5)-(6,6)'.

What my code does is it correctly adds the dashes but the errors I am getting is that is doesn't read in the first value and it also ends up with an extra dash at the end.

My code returns a string that looks like '(4,4)-(5,5)-(6,6)-' which is wrong. I have shown my code above and need help fixing this.

Ouss4
  • 479
  • 4
  • 11
brian012
  • 193
  • 1
  • 2
  • 12

1 Answers1

4

You are on the right track. However, it'd be better to use .join() in this case to not append - to the last tuple in the list:

>>> def display(xs):
...    return "-".join(map(str, xs))

>>> display([(2,3),(4,4),(5,5),(6,6)])
'(2, 3)-(4, 4)-(5, 5)-(6, 6)'

If you don't want the whitespace between tuple items, you gotta format them yourself:

>>> def display(xs):
...     return "-".join("({},{})".format(*t) for t in xs)

>>> display([(2,3),(4,4),(5,5),(6,6)])
'(2,3)-(4,4)-(5,5)-(6,6)'

Here is the modified version of your function:

>>> def display(xs):
...     string1 = ""
...     for i in range(len(xs)):
...         string1 += str(xs[i])
...         if i != len(xs) - 1:
...             string1 += "-"
...     return string1
Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119