0

I'm now to python and I wanted to know the correct way of doing this. I'm trying to add pieces to make a full string but I get symbols in the string output

def responseLibrary(days, hours, minutes, seconds):
global globalSeconds
response = globalSeconds, " seconds equals "

if days > 0:
    response += days, " days "
if hours > 0:
    response += hours, " hours "
if minutes > 0:
    response += minutes, " minutes "
if seconds > 0:
    response += seconds, " seconds "
return response

The output I get looks like this

(10, ' seconds equals ', 10, ' seconds ')
D Rodriguez
  • 41
  • 1
  • 7
  • Use `+` to combine the strings, not `,` – xrisk Sep 21 '18 at 03:50
  • 1
    Possible duplicate of [How do I append one string to another in Python?](https://stackoverflow.com/questions/4435169/how-do-i-append-one-string-to-another-in-python) – Matt Sep 21 '18 at 03:50

2 Answers2

0

At the end, you could use

return ''.join(map(str, response))

What's happening is that when you say response = globalSeconds, " seconds equals " You're creating a tuple. When you use the print function, you're not passing in a single string created by some sort of comma-based joining operation. You're passing in multiple arguments, and the print function handles them appropriately.

If you wanted to join strings all the way through, the + operator allows for string concatenation. It is typically more efficient to use .join() rather than a large number of concatenations however.

For reference, this answer uses the builtin str.join() method, documented here. It also uses the map() builtin documented here. What they're doing is basically as follows:

  1. By the end of your program, response is a tuple of different values.
  2. Not all of those values are strings (notice that you never converted any integers to a different type).
  3. The builtin .join() method requires an iterable of strings for its input.
  4. The line map(str, response) is roughly the same as (str(x) for x in response). Now we have an iterable object of string representations of the values we want to join together.
  5. The .join() method takes all of those strings and concatenates them into one giant string like you want.
  6. Note the '' at the beginning of .join(). That's the separator we're using between each of the strings we're joining. You could just as easily use spaces or commas or anything else like ', '.join(...).
Hans Musgrave
  • 6,613
  • 1
  • 18
  • 37
0

You can't join strings and ints with a comma. That gives you a tuple, as your output shows.

You need to convert the ints to strings. One way is: response += str(seconds) + " seconds"

Another way would be to use the string format function: response += "{} seconds".format(seconds)

AShelly
  • 34,686
  • 15
  • 91
  • 152