defsplit(target, s): """ split str according special divider :param target: str :param s: str :return: list """ try: if s: start = 0 res = [] for i inrange(len(s)): if s[i] == target: res.append(s[start:i]) start = i + 1 res.append(s[start:]) return res else: raise ValueError("s is not allowed to be empty!") except Exception as e: print(e)
join
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
defjoin(link, lists): """join items in the list by special linker :param link: str :param lists: list :return: str """ try: iflen(lists): res = '' for i in lists: res += (i+link) iflen(link): res = res[:-len(link)] return res else: raise ValueError("lists is not allowed to be empty!") except Exception as e: print(e)
replace
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
defreplace(target, replce, string): """replace character in the str with anoteher charcter :param target: str :param replace: str :param string: str :return: str """ try: if target and replace and string: segments = split(target, string) res = join(replce, segments) return res else: raise ValueError("paramter error") except Exception as e: print(e)
# 输入数据检测 if _str[0] == '-': _str = _str[1:] flag = False for _char in _str: tmp = ord(_char) if tmp < ord_0 or tmp > ord_9: raise ValueError
# string to int res = 0 count = 0 is_valid = True for item in _str[::-1]: is_valid = True # 做溢出判断 -2147483648 < int32 < 2147483647 # 负数溢出判定 or 正数溢出判定 tmp = (ord(item) - ord_0) * (10**count) if (not flag and res < 147483648and tmp <= 2000000000) or (flag and res < 147483647and tmp <= 2000000000): pass# 满足条件,不做处理。 else: is_valid = False
if is_valid: res += tmp count += 1 else: raise ValueError
defscale_Convert(number, base): prefix = {2: "0b", 8: "0o", 16: "0x"} hash_map = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f'] b = [] whileTrue: s = number // base y = number % base b = b + [y] if s == 0: break number = s b.reverse() b = [str(hash_map[i]) for i in b] return prefix[base] + "".join(b)
输出
1 2 3 4 5 6 7 8 9
>>> res = scale_Convert(160, 2) >>> res '0b10100000' >>> res = scale_Convert(160, 8) >>> res '0o240' >>> res = scale_Convert(160, 16) >>> res '0xa0'
其他
2进制
8进制
10进制
16进制
2进制
-
bin(int(n,8))
bin(int(n,10))
bin(int(n,16))
8进制
oct(int(n,2))
-
oct(int(n,10))
oct(int(n,16))
10进制
int(n,2)
int(n,8)
-
int(n,16)
16进制
hex(int(n,2))
hex(int(n,8))
hex(int(n,10))
-
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# 2进制转8进制,先将2进制转成10进制,再将其10进制形式转换成8进制 >>> a = int('0b10100000', 2) >>> a 160 >>> oct(a) '0o240' # 一次性完成 >>> oct(int('0b10100000', 2)) '0o240'
# 8进制转16进制,先将8进制转成10进制,再将其10进制形式转换成16进制 >>> a = int('0o240', 8) >>> a 160 >>> hex(a) '0xa0' # 一次性完成 >>> hex(int('0o240', 8)) '0xa0'