Python: how to print range a-z?
311,384
Solution 1
>>> import string
>>> string.ascii_lowercase[:14]
'abcdefghijklmn'
>>> string.ascii_lowercase[:14:2]
'acegikm'
To do the urls, you could use something like this
[i + j for i, j in zip(list_of_urls, string.ascii_lowercase[:14])]
Solution 2
Assuming this is a homework ;-) - no need to summon libraries etc - it probably expect you to use range() with chr/ord, like so:
for i in range(ord('a'), ord('n')+1):
print chr(i),
For the rest, just play a bit more with the range()
Solution 3
Hints:
import string
print string.ascii_lowercase
and
for i in xrange(0, 10, 2):
print i
and
"hello{0}, world!".format('z')
Solution 4
for one in range(97,110):
print chr(one)
Solution 5
Get a list with the desired values
small_letters = map(chr, range(ord('a'), ord('z')+1))
big_letters = map(chr, range(ord('A'), ord('Z')+1))
digits = map(chr, range(ord('0'), ord('9')+1))
or
import string
string.letters
string.uppercase
string.digits
This solution uses the ASCII table. ord
gets the ascii value from a character and chr
vice versa.
Apply what you know about lists
>>> small_letters = map(chr, range(ord('a'), ord('z')+1))
>>> an = small_letters[0:(ord('n')-ord('a')+1)]
>>> print(" ".join(an))
a b c d e f g h i j k l m n
>>> print(" ".join(small_letters[0::2]))
a c e g i k m o q s u w y
>>> s = small_letters[0:(ord('n')-ord('a')+1):2]
>>> print(" ".join(s))
a c e g i k m
>>> urls = ["hello.com/", "hej.com/", "hallo.com/"]
>>> print([x + y for x, y in zip(urls, an)])
['hello.com/a', 'hej.com/b', 'hallo.com/c']
Author by
hhh
Updated on July 08, 2022Comments
-
hhh almost 2 years
1. Print a-n: a b c d e f g h i j k l m n
2. Every second in a-n: a c e g i k m
3. Append a-n to index of urls{hello.com/, hej.com/, ..., hallo.com/}: hello.com/a hej.com/b ... hallo.com/n
-
Alex Willison almost 7 yearsTo make this a tuple (which is immutable) in Python 3:
tuple(string.ascii_lowercase)
-
johk95 over 6 yearsI believe string.ascii_lowercase already worked in python 2.x, so to be sure just always use ascii_lowercase.
-
John La Rooy over 6 years@johk95, actually
str.lowercase
is locale dependent so wasn't the best choice in the first place. I've replaced it in my answer -
jonespm about 5 yearsIt looks like string.letters was removed in Python 3 and only string.ascii_letters, not exactly the same, is available
-
Jeroen Heier over 4 yearsWelcome to StackOverflow. Try to explain more clearly why this is a complete answer to the question.
-
hmacias about 4 yearsThanks. I like it how you build this.
-
Schroter Michael about 4 yearsHi, would be able to tell me whether is this only available in English? cant I get the same for other languages as well? Thanks & Best Regards