codewars5 Replace With Alphabet Position

Instructions
Welcome.

In this kata you are required to, given a string, replace every letter with its position in the alphabet.

If anything in the text isn’t a letter, ignore it and don’t return it.

“a” = 1, “b” = 2, etc.
Example
alphabet_position("The sunset sets at twelve o' clock.")
Should return “20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11” (as a string)
Solution:

def position_number(word):   #每一个单词所对应的数字
    word_position=''
    for l in word: 
        if ord(l)>=97 or ord(l)<=122:     #小写字母在字母表中的位置
            word_position+=(str(ord(l)-96))
        elif ord(l)>=65 or ord(l)<=90:    #大写字母在字母表中的位置
            word_position+=(str(ord(l)-64))
    return word_position
def alphabet_position(text):
    words_position=''
    for word in text.split():
        words_position+=(str(position_number(word)))
    return words_position

输出错误


借鉴

def alphabet_position(text):
    letters = []
    for s in text:
        c = ord(s)
        if c >= 65 and c <= 90:
            c -= 64
        elif c >= 97 and c <= 122:
            c -= 96
        else:
            continue
        letters.append(str(c))
    return ' '.join(letters)

更正

def alphabet_position(text):
	word_position=[]
	for l in text: 
    	if ord(l)>=97 and ord(l)<=122:     #小写字母在字母表中的位置
        	word_position.append(str(ord(l)-96))
    	elif ord(l)>=65 and ord(l)<=90:    #大写字母在字母表中的位置
        	word_position.append(str(ord(l)-64))
    	else:
        	continue
	return ' '.join(word_position)

需要注意的问题

  1. 逻辑连接次and、or使用时多确定一次,选择是否正确;
  2. 根据输出格式要求选择创建列表还是字符串,注意空白字符输出情况;
  3. 程序中的 l in text,l 表示text中的字符,不是text中的某个单词。

Best practice:

def alphabet_position(text):
	return ' '.join(str(ord(c) - 96) for c in text.lower() if c.isalpha())
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值