For example, 1
should give me alphabet a
,
2 > b
3 > c
...
26 > a
And 27 should give an again
28 > b
.. Till 9999
The below code only works with 26 numbers
import string
di=dict(zip(string.letters,[ord(c)%32 for c in string.letters]))
di['c']
Output is 3
.
Can anyone please help?
this would do
def num2char(num):
return chr(((num-1) % 26) + ord('a'))
you don't need to go through a dictionary to convert numbers to letters that way. You can apply the modulo to positions in a string of letters
letters = "abcdefghijklmnopqrstuvwxyz"
for i in range(1,1000):
print(i,">",letters[(i-1)%26])
output:
1 > a
2 > b
3 > c
4 > d
5 > e
6 > f
7 > g
8 > h
9 > i
10 > j
11 > k
12 > l
13 > m
14 > n
15 > o
16 > p
17 > q
18 > r
19 > s
20 > t
21 > u
22 > v
23 > w
24 > x
25 > y
26 > z
27 > a
28 > b
29 > c
...
See if either one of these is what you're looking for:
print (ord ('a') - 96)
print (chr (1 + 96))
Your data structure is odd. If your input alphabet contains 9999 symbols, you need a dictionary of that many elements. But actually you don't really need a dictionary at all, just the observation that the input number modulo 26 plus 1 maps to the character codes starting at a
.
def strmap(numbers):
base = ord('a')
mapped = [chr(base + (n-1)%26) for n in numbers]
return ''.join(mapped)
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.