1

I have a table in which all the 120 fields have got type varchar(75). I have coded like this.

sql = "create table " + tableName + "("
for i in range(len(flds)):
    if i == len(flds) - 1:
        sql += flds[i] + " varchar(75))"
    else:
        sql += flds[i] + " varchar(75), "

Is it possible to get a one-liner for it?

Thanks!

2 Answers 2

2

First, let's use join so we don't need the commas and if. And, while we're at it, we can just loop over flds instead of range(len(flds)):

columns = []
for fld in flds:
    columns.append(fld + " varchar(75)"

Of course this means we have to add the ) on at the end:

sql += ', '.join(columns) + ')'

Now we can turn that loop into a comprehension:

columns = (fld + " varchar(75)" for fld in flds)

And now, we can inline that into the join:

sql += ', '.join(fld + " varchar(75)" for fld in flds) + ')'

And now, we have two lines that can obviously be combined into one:

sql = "create table " + tableName + "(" + ', '.join(fld + " varchar(75)" for fld in flds) + ')'

But that's way over 80 characters, so probably better to write it as two lines anyway. I'd probably do it like this:

columns = ', '.join(fld + " varchar(75)" for fld in flds)
sql = "create table " + tableName + "(" + columns + ")"

And finally, let's use an f-string instead of concatenating with +, which makes things only a little shorter, but a lot more readable.

columns = ', '.join(f'{fld} varchar(75)' for fld in flds)
sql = f'create table {tableName} ({columns})'
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for explaining.
2

You can use join with format:

v = "create table {} ({} varchar(75));".format(tableName, " varchar(75), ".join(flds))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.