Insertig a string into a tuple

Hello all,

So I have a tuple which is attained from my views.py document and is called as a for loop from my template (HTML Template).

This all works perfectly & as expected.

However, I want to take this one step further and put the word "and" in between the second from last and the last item in the tuple. i.e.

> United Kingdom, Germany, United States, France and Canada

I currently have the following code. This is the code which is called as a for loop from my HTML template.

def legal__privacy_statement(request):
...
...
...
    context = {     
        ...
        ....
        ....
        'datacountry'   : ['United Kingdom','Germany','United States', 'France', 'Canada'],
        ....
    }
return render (request, 'privacy-statement.html', context)

Playing around with this, I am thinking of separating the last item in the tuple, placing the word “and” & then appending the last tuple item on the end. I’m thinking something like:

'datacountry'   : ['United Kingdom', 'Germany', 'United States', 'France', 'Canada'],
a = datacountry[ : -1 ]
b = datacountry[ - 1  ]
c = a + "and" + b

return{c}

So I will get the result:

United Kingdom, Germany, United States, France, and Canada

However, Python is not McLoving the fact that I am mixing a string and a tuple together.

Is there a way which I’m missing here in which I can place and “and” into the tuple?

Many thanks.

As you saw, you can’t add a string to a tuple. You need to put "and" inside its own tuple, so that you’re adding tuples to tuples.

c = a + ("and",) + b

1 Like

Three operators are useful when constructing strings:

  1. the concatenation operator (+)
  2. join() to concatenate a collection of strings into a single string
  3. F-strings

Thus:
F"{', '.join( country[ :-1 ] )}, and {country[ -1 ]}"

F-strings make it somewhat easier to visualise the result - which enables (me) us to remember the spaces and other characters required as part of the final result.

Note that if you want to handle corner cases, e.g. zero or one or two elements, or offer the options for different conjunctions or separators, or automatically stringify inputs that can be converted to strings, it’s a little more works, so you’ll want to wrap things up in a little function:

Adding support for an Oxford comma (only in cases where it would make sense, e.g. avoiding “a, or b”) is left as an exercise to the reader.