Python习题集(十七)

简介: Python习题集(十七)

每天一习题,提升Python不是问题!!有更简洁的写法请评论告知我!

https://www.cnblogs.com/poloyy/category/1676599.html

 

题目


写一个函数alphabet_index,该函数参数是1个字符串,
要求该函数返回一个新字符串,里面是 参数字符串中每个字母依次对应的 数字。如果是非字母,则忽略它
字母"a" 和"A" 都对应 1, "b"和"B"都对应2, "c"和"C"对应3, 依次类推
比如
alphabet_index("Wow, does that work?")
➞ "23 15 23 4 15 5 19 20 8 1 20 23 15 18 11"
alphabet_index("The river stole the gods.")
➞ "20 8 5 18 9 22 5 18 19 20 15 12 5 20 8 5 7 15 4 19"
alphabet_index("We have a lot of rain in June.")
➞ "23 5 8 1 22 5 1 12 15 20 15 6 18 1 9 14 9 14 10 21 14 5"


解题思路


  1. 将字符串统一为大写字母
  2. 需要设置一个对比值
  3. 大写A的ASCII码为65,但A对应1,所以设置一个对比值为64
  4. 循环字符串,如果是字母则换算出它的ASCII码,再减去对比值

 

答案


def alphabet_index(strs):
    strs = strs.upper()
    temp = 64
    res = ""
    for i in strs:
        if i.isalpha():
            res += str(ord(i) - temp) + " "
    print(res)
alphabet_index("Wow, does that work?")
alphabet_index("The river stole the gods.")
alphabet_index("We have a lot of rain in June.")
相关文章
|
2月前
|
物联网 Python
2024年Python最全信息技术导论——物联网技术习题整理(1),Python面试题库
2024年Python最全信息技术导论——物联网技术习题整理(1),Python面试题库
2024年Python最全信息技术导论——物联网技术习题整理(1),Python面试题库
|
2月前
|
存储 Python
【python】习题第10周题解
【python】习题第10周题解
28 1
|
2月前
|
Python
【python】习题第9周
【python】习题第9周
29 0
|
2月前
|
自然语言处理 Python
【python】习题第7周(上)
【python】习题第7周(上)
47 1
|
2月前
|
Python
【python】习题 1-5周(上)
【python】习题 1-5周(上)
16 1
|
2月前
|
Python
【python】习题 第10周
【python】习题 第10周
36 0
|
2月前
|
数据安全/隐私保护 Python
【python】习题第8周
【python】习题第8周
26 0
|
2月前
|
Python
【python】习题第7周(下)
【python】习题第7周(下)
24 0
|
2月前
|
Python
【python】习题 6-10周(下)
【python】习题 6-10周(下)
29 0
|
2月前
|
自然语言处理 数据安全/隐私保护 Python
【python】习题 6-10周(中)
【python】习题 6-10周(中)
35 0