names = ['David', 'Peter', 'Michael', 'John', 'Bob']
for i in range (len (names)):
print("{}.{}".format(i + 1, names[i]))
Python list index references cannot be strings. Iterating through the list via a for loop using integers rather than the indexes themselves (which are strings) will solve this issue. This is an example where the error message is very useful in diagnosing the problem.
Answer from Reece on Stack Overflownames = ['David', 'Peter', 'Michael', 'John', 'Bob']
for i in range (len (names)):
print("{}.{}".format(i + 1, names[i]))
Python list index references cannot be strings. Iterating through the list via a for loop using integers rather than the indexes themselves (which are strings) will solve this issue. This is an example where the error message is very useful in diagnosing the problem.
Python's for...in statement is like like a foreach in other languages. You want enumerate to get the indexes.
for i, name in enumerate(names):
print("{}. {}".format(i+1, name))
If you want to print them all on one line, use the end kwarg.
for i, name in enumerate(names):
print("{}. {}".format(i+1, name), end=" ")
print() # for the final newline
1. David 2. Peter 3. Michael 4. John 5. Bob
Python string formatting: For loops? - Stack Overflow
String formatting in a loop
Python: Loop: formatting string - Stack Overflow
list - How to loop with string formatting in Python? - Stack Overflow
Videos
mystuff = [1, 2, "Foo", 34, 42, "Ni", 12, 14, "Blue"]
for x in zip(*[iter(mystuff)]*3):
print "%d %d %s"%x
Or using .format
mystuff = [1, 2, "Foo", 34, 42, "Ni", 12, 14, "Blue"]
for x in zip(*[iter(mystuff)]*3):
print "{0} {1} {2}".format(*x)
If the format string is not hardcoded, you can parse it to work out how many terms per line
from string import Formatter
num_terms = sum(1 for x in Formatter().parse("{0} {1} {2}"))
Putting it all together gives
mystuff = [1, 2, "Foo", 34, 42, "Ni", 12, 14, "Blue"]
fmt = "{0} {1} {2}"
num_terms = sum(1 for x in Formatter().parse(fmt))
for x in zip(*[iter(mystuff)]*num_terms):
print fmt.format(*x)
I think join is the most similar feature in Python:
(format t "~{~D, ~}" foo)
print(foo.join(", "))
It's a little worse when you have multiple items inside, as you see, though if you have a group-by function (which is really useful anyway!), I think you can make it work without too much trouble. Something like:
mystuff = [1, 2, "Foo", 34, 42, "Ni", 12, 14, "Blue"]
print(["%d %d %s" % x for x in group(mystuff, 3)].join("\n"))
Hello, I have another probably very trivial question
I was doing something unrelated and ended up with code similar to this:
...
for result in db:
logging.info('RESULTS: {}'.format(result))What I want here would be
RESULTS:
a
b
c
...But, of course, this doesn't work
My first instinct was something like this:
...
log = 'RESULTS:'
for result in db:
log = 'log' + result \n
logging.info(log)
Which works, but I read about and string concatenation isn't efficient at all. In this particular case the database is really tiny, so it's fine. But I was wondering, how could I achieve the same for a relatively large (not really huge) database? Is there a way to concatenate using .format?
Did you mean something like this?
my_string = "".join(["_%d_" % i for i in xrange(1,5)])
That creates a list of the substrings as requested and then concatenates the items in the list using the empty string as separator (See str.join() documentation).
Alternatively you can add to a string though a loop with the += operator although it is much slower and less efficient:
s = ""
for x in range(1,5):
s += "_%d_" % x
print s
print("_" + "__".join(map(str, xrange(1,5)))) +"_"
_1__2__3__4_
In [9]: timeit ("_" + "__".join(map(str,xrange(1,5)))) +"_"
1000000 loops, best of 3: 1.38 µs per loop
In [10]: timeit "".join(["_%d_" % i for i in xrange(1,5)])
100000 loops, best of 3: 3.19 µs per loop
I am currently learning the string formatting topic and I have searched many places only to get *args and *kwargs (completely unrelated to my question) as my answer. Coming back to my question....
Let's say I have a code to convert decimal numbers to binary, octal and hexadecimal. I wrote the code something like this
num = int(input("Enter an integer: "))
print("Binary of {0} is {1:b}".format(num, num))
print("Hexadecimal of {0} is {1:x}".format(num, num))
print("Octal of {0} is {1:o}".format(num, num))Here, in the string format method, I am passing 'num' twice to reflect in the printed message. Is there anyway to pass 'num' once to all the placeholders {} in the string?
One more example:
can you can a can as a canner can can a can
For a statement like this, you can code something like below which has repeating "can"s. Instead I want to pass a single string variable for all the placeholders
print("{0} you {1} a {2} as a canner {3} {4} a {5}".format("can", "can", "can", "can", "can", "can"))Note: Please do suggest a solution to the above, if one such exists. If it doesn't, you can say no. Please please please avoid statements like "You can directly print the string as such instead of going through this ordeal!"