i'd like to know: what's the difference between these two:
return "-".join([c.upper() + c.lower() * i for i,c in enumerate(txt)])
return "-".join([c.upper() + c.lower() * i for c,i in enumerate(txt)])
I just changed the 'i' with the 'c' and the whole code doesn't work. Is there a simple explanation?
Yes. enumerate()
yields pairs of (index, item)
from a given iterable.
For a string "hello"
, it would return (formatted as a list)
[
(0, 'h'),
(1, 'e'),
(2, 'l'),
(3, 'l'),
(4, 'o'),
]
For the sake of simplicity, let's look at the first item only, (0, 'h')
.
If you use i, c
to unpack this, i
's value will be 0
, and c
's value will be 'h'
, and c.lower()
etc. makes sense, as does multiplication with the number i
.
If you use c, i
to unpack this, c
's value will be 0
, and i
's value will be 'h'
, and c.lower()
no longer exists since c
is a number and i
is a string.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.