Python
3分钟练习
连续AscII转换
昨天我们已经成功的实现了将连续(无论带空格还是不带空格)的字符串,提取出每个字母元素,并且将这些字母元素转换位对应的 AscII 码,鉴于我们吉米同学提出来的偷懒方法,我们今天就来调整一下输出格式,以此达到减少输出结果搬运的操作。
之前的课程内容
def Severalord(sentence):
words = sentence.split()
for word in words:
l = len(word)
for i in range(l):
asciibak = ord(word[l-i-1])
print(asciibak)
print('========')
print('自定义输入连续字符串')
uesri = input()
uesro = Severalord(uesri)
print(uesro)
这里我们去掉昨天制作出来的函数中多余的注释和自测试操作内容。不过这里有点问题,最后输出的 AscII 转换中出现一个 None ,这是因为我们使用了 print(uesro) 这个 Severalord() 函数是不会返回值的,所以这个时候, uesro 是一个空变量,所以 print 它只会显示一个 none
自定义输入连续字符串
改造自定义函数
我们使用倒序输出字符串那一课学习到的知识,对每个字母单独使用 ord() 函数转换成 AscII 码,先将当前生成的 newword(内部装载着刚刚转换过来的AscII码)通过 str() 函数转换为 字符串,再通过append , 将内容追加到 bak 列表中。
然后使用 join 操作,将变量 bak 使用 Space 连接起来,然后输出。
def txt(sentence):
words = sentence.split()
space=' '
for word in words:
bak= []
l = len(word)
for i in range(l):
newword = ord(word[l-i-1])
bak.append(str(newword))
bak.reverse()
print(space.join(bak))
txt('ABCD1234')
空格分割一行 AscII 码
我们可以在自定义函数外增加这几行代码,将该程序段改写成自由输入的 AscII 转换脚本。
print('自定义输入连续字符串')
uesri = input()
txt(uesri)
完整代码和效果展示
def txt(sentence):
words = sentence.split()
space=' '
for word in words:
bak= []
l = len(word)
for i in range(l):
newword = ord(word[l-i-1])
bak.append(str(newword))
bak.reverse()
print(space.join(bak))
print('自定义输入连续字符串')
uesri = input()
txt(uesri)