简体   繁体   中英

Python : how to count amount of letters of alphabet in string in parts

How to count the amount of letters in this string between the different parts? And the other way around: how to get the alphabetical string representation when the numbers are given?

Input: 'AG HO P Q-Z'

Output: (7, 8, 1, 10)

  q = list()

    for i in seq:
        if i is char:
            n = ord(i+1) - ord(i)
            q.append(n)

You can do this:

input_string = 'A-G H-O P Q-Z'
input_string = input_string.split()

q = []
for dletter in input_string:
    if '-' in dletter:
        q.append(1 + ord(dletter[2]) - ord(dletter[0]))
    else:
        q.append(1)

Alternatively without the if statement:

input_string = 'A-G H-O P Q-Z'
input_string = input_string.split()

q = []
for dletter in input_string:
    q.append(1 + ord(dletter[-1]) - ord(dletter[0]))

But this is a very good answer

a = "A-G  N B-Z"
a = a.split()
b = []
for i in a:
    b.extend([i.split("-")])
print(b)
for lists in b:
    if len(lists) > 1:
        print(lists, ":", ord(lists[1]) - ord(lists[0]) + 1)
    else:
        print(lists, ":", 1)

Output

[['A', 'G'], ['N'], ['B', 'Z']]
['A', 'G'] : 7
['N'] : 1
['B', 'Z'] : 25

Using list comprehension

a = "A-G  N B-Z"

b = [i.split("-") for i in a.split()]

print(b)
for lists in b:
    if len(lists) > 1:
        print(lists, ":", ord(lists[1]) - ord(lists[0]) + 1)
    else:
        print(lists, ":", 1)

Output

[['A', 'G'], ['N'], ['B', 'Z']]
['A', 'G'] : 7
['N'] : 1
['B', 'Z'] : 25

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM