python外卷(12)-sort(),sorted(),ord(),chr(), eval()

1 sort(),sorted()

sort() 是list的方法,对已经存在的列表进行操作,无返回值

a=[3,2,4,1]
b=["c","a","b"]
print (a.sort(),b.sort())
# 输出 (None, None)
a.sort()
b.sort()
print (a,b)
# 输出 ([1, 2, 3, 4], ['a', 'b', 'c'])

sorted() 可以对所有可迭代的对象进行排序操作,返回一个新的list,不是对原变量进行原地操作。

c="cab"
print (sorted(c))
# 输出 ['a', 'b', 'c']

参考资料:https://www.runoob.com/python/python-func-sorted.html

2 ord(), chr()

ord()用来返回字符对应的ascii码

print(ord("a"))
# 输出:97

# 可用于计算字符之间的距离:
print(ord("c")-ord("a"))
# 输出:2
print("a"-"c")
# 输出:TypeError: unsupported operand type(s) for -: 'str' and 'str'

chr()用来表示ascii码对应的字符,其输入是数字,可以是:十进制,十六进制

print(chr(97))
# 输出:a
print(chr(0x61))
# 输出:a

参考资料:https://www.cnblogs.com/sui776265233/p/9103251.html

3 eval()

eval 函数会将字符串当成 有效表达式 来 求值 , 并返回计算结果.

简单案例:计算器.要求用户输入一个 加减乘除混合运算,程序返回一个计算结果

input_str=input("请输入算术题")
print(eval(input_str))

# 输入:(1+3)*5
# 输出:15 完全不需要解析表达式中的内容,自动转换计算. 

注意事项:
在开发时,千万不要使用eval()直接转换**input()**的结果

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值