Wait, I have another comment...

On Wed, Oct 28, 2015 at 02:48:05PM +0000, Flynn, Stephen (L & P - IT) wrote:

>       I'm iterating through a list and I'd like to know when I'm at
> the end of the said list, so I can do something different. For example
[...]
> For context, I'm working my way through a (csv) file which describes
> some database tables. I'm building the Oracle DDL to create that table
> as I go. When I find myself building the last column, I want to finish
> the definition with a ");" rather than the usual "," which occurs at the
> end of all other column definitions...

Then you don't need to know when you're at the end of the list. See 
below.

But firstly, and MOST IMPORTANTLY, how are you sanitizing your input?

http://bobby-tables.com/

Code injection attacks are now #1 risk factor for code, above buffer 
overflows.

So, assuming you have sanitized your input, or trust it more than you 
trust your own code (you run tests on your own code, right?), let's see 
how to build up a string like:

"FUNCTION(a,b,c,d,e);"

with some variable number of string arguments a, b, c, ... 


args = ["5", "2", "7", "1", "0", "3"]
result = "FUNCTION(%s);" % ','.join(args)


This will do the right thing whether there is one argument or twenty, or 
even no arguments at all.

The "join" method inserts the first string *between* each of the list 
items. It deals correctly with the "no items" and "one item" cases:

py> "--".join([])
''
py> "--".join(["spam"])
'spam'
py> "--".join(["spam", "eggs"])
'spam--eggs'
py> "--".join(["spam", "eggs", "cheese"])
'spam--eggs--cheese'


so you don't have to worry about counting items or determining the last 
item, you just join them. 


-- 
Steve
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to