Python刷题笔记(3)- 16进制和ascii码互转
2015-11-18 17:19
721 查看
今天看了下等级标示,原来kyu上面还有dan的等级,升级路漫漫,今天是5kyu题目
Example
2、16进制转换字符串,间隔为2历遍字符串,然后将16进制字符串转换成10进制数字,用char()函数转换为ASCII码加入列表,然后把列表合成字符串返回。
3、int(str,16)可以实现字符串转换成16进制,str()实现转换字符串,hex()函数转换为16进制,但是返回的是0x00形式
@staticmethod
def to_ascii(h):
list_s = []
for i in range(0,len(h),2):
list_s.append(chr(int(h[i:i+2].upper(),16)))
return ''.join(list_s)
@staticmethod
def to_hex(s):
list_h = []
for c in s:
list_h.append(str(hex(ord(c)))[-2:]) #取hex转换16进制的后两位
return ''.join(list_h)
题目:
Write a module Converter that can take ASCII text and convert it tohexadecimal. The class should also be able to take hexadecimal andconvert it to ASCII text.Example
Converter.to_hex("Look mom, no hands") => "4c6f6f6b206d6f6d2c206e6f2068616e6473" Converter.to_ascii("4c6f6f6b206d6f6d2c206e6f2068616e6473") => "Look mom, no hands"
中文简介:
就是写个ASCII码和16进制的转换器,可以互相转换。想法:
1、字符串转16进制,直接使用ord()函数然后逐个转换为16进制,再将16进制数转化成字符串形式加入到列表,再把列表合成字符串返回2、16进制转换字符串,间隔为2历遍字符串,然后将16进制字符串转换成10进制数字,用char()函数转换为ASCII码加入列表,然后把列表合成字符串返回。
3、int(str,16)可以实现字符串转换成16进制,str()实现转换字符串,hex()函数转换为16进制,但是返回的是0x00形式
实现:
class Converter():@staticmethod
def to_ascii(h):
list_s = []
for i in range(0,len(h),2):
list_s.append(chr(int(h[i:i+2].upper(),16)))
return ''.join(list_s)
@staticmethod
def to_hex(s):
list_h = []
for c in s:
list_h.append(str(hex(ord(c)))[-2:]) #取hex转换16进制的后两位
return ''.join(list_h)
比较总结:
提交后看到别人的方法实在是简单。。直接使用系统函数encode("hex")和decode("hex")就解决了。。感觉有点作弊啊。。相关文章推荐
- 关于python编码的一些理解
- LeetCode OJ 系列之26 Remove Duplicates from Sorted Array --Python
- python的参数
- 使用Python 2.7实现的垃圾短信识别器
- python用requests请求百度接口报“SSL: CERTIFICATE_VERIFY_FAILED”
- Python学习指南
- python3输出unicode
- Python中list的实现
- Python处理Json报文
- 【python】class之子类
- python 抽象类、抽象方法的实现
- 安装python MySQLdb报错:pymemcompat.h:10:20: 致命错误的解决
- scikit学习心得——Isotonic Regression
- Python编写微信打飞机小游戏(十二)
- Difference between Range and Xrange in Python
- 折腾Ipython
- 第一个Python程序——博客自动访问脚本
- Python基础学习-爬虫小试2
- python插件
- Python学习小记