字符串转数组列表
def strTolist (str ):
ans = list (str )
for i in range (len (ans)):
ans[i] = ord (ans[i])
return ans
str ='Hello'
print (strTolist(str ))
16进制字符串转字符串
def hexstrTostr (hexstr ):
byte_str = bytes .fromhex(hexstr)
return byte_str.decode("utf-8" )
hexstr = "48656c6c6f"
print (hexstrTostr(hexstr))
16进制字符串转列表
def hexstrTolist (hexstr ):
ans = []
if len (hexstr) % 2 == 1 :
print ("两两分组要双数字符串" )
else :
for i in range (0 , len (hexstr), 2 ):
ans.append(int (hexstr[i:i + 2 ], 16 ))
print ("分组后列表:" , ans)
hex_data_list = ["0x{:02x}" .format (item) for item in ans]
tmp = "," .join(hex_data_list)
print ('分组后列表16进制显示: [' + tmp + ']' )
return ans
hexstr = "48656c6c6f"
hexstrTolist(hexstr)
字符串中大写转小写
strs.lower()
字符串中大写转小写
strs.upper()
字符串大小写置换
def ulsub (old_strs ):
new_strs = ''
for str in old_strs:
if str .isupper():
new_strs += chr (ord (str ) + 32 )
elif str .islower():
new_strs += chr (ord (str ) - 32 )
else :
new_strs += str
return new_strs
倒序输出
for i in range (10 ,1 ,-1 ):
print (i)
列表反转
data_list[::-1 ]
数组列表通过ASCII码转为字符串
def listTostr (table ):
ans = ''
for item in table:
ans = ans + chr (item)
return ans
lt = [0x48 ,0x65 ,0x6c ,0x6c ,0x6f ]
print (listTostr(lt))
base64换表
def base64_encode (message,base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" ):
message_bytes = message.encode('utf-8' )
padding = 3 - (len (message_bytes) % 3 )
if padding == 3 :
padding = 0
message_bytes += b'\x00' * padding
encoded_chars = []
for i in range (0 , len (message_bytes), 3 ):
value = (message_bytes[i] << 16 ) + (message_bytes[i + 1 ] << 8 ) + message_bytes[i + 2 ]
for j in range (4 ):
index = (value >> ((3 - j) * 6 )) & 63
encoded_chars.append(base64_chars[index])
for i in range (padding):
encoded_chars[-(i + 1 )] = '='
return '' .join(encoded_chars)
def base64_decode (encoded_message,base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" ):
decoded_bytes = bytearray ()
for i in range (0 , len (encoded_message), 4 ):
value = 0
for j in range (4 ):
if encoded_message[i + j] == '=' :
value <<= 6
else :
value <<= 6
value += base64_chars.index(encoded_message[i + j])
for j in range (2 , -1 , -1 ):
decoded_bytes.append((value >> (j * 8 )) & 255 )
while decoded_bytes[-1 ] == 0 :
decoded_bytes.pop()
ans = None
try :
ans = decoded_bytes.decode('utf-8' )
except Exception as e:
print ("[*]解码失败" )
return ans
message = "Hello, World!"
encoded_message = base64_encode(message,base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" )
print ("Encoded:" , encoded_message)
decoded_message = base64_decode(encoded_message,base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" )
print ("Decoded:" , decoded_message)
16进制字符串转10进制整数
hexstr = "1A3F"
decimal_number = int (hexstr, 16 )
print (decimal_number)
10进制整数转16进制字符串
hex_result = hex (6719 )
print (hex_result)
字符串循环移位
def strloopmove (old_strs, n, direction=True ):
"""
字符串循环移动
:param old_strs: 待移动字符串
:param n: 移动距离
:param direction: 方向,True表示左移,True表示右移
:return: 循环移动后的字符串
"""
new_strs = ''
if direction == True :
for str in old_strs:
new_strs += old_strs[(old_strs.index(str ) + n) % len (old_strs)]
else :
for str in old_strs:
new_strs += old_strs[(old_strs.index(str ) - n) % len (old_strs)]
return new_strs
位置映射
def create_position_mapping (old_table, new_table) :
"""
创建位置映射字典,仅显示 old_table 和 new_table 中的位置关系。
参数:
old_table (str) : 原始字符表。
new_table (str) : 新的字符表。
返回:
dict: 一个包含旧表位置到新表位置映射的字典。
抛出:
ValueError: 如果old_table和new_table不匹配,或包含重复字符。
"""
# 检查是否有重复字符
if len (set (old_table)) != len(old_table):
raise ValueError ("old_table contains duplicate characters" )
if len (set (new_table)) != len(new_table):
raise ValueError ("new_table contains duplicate characters" )
# 检查是否能够相互找到字符
if set (old_table) != set (new_table):
raise ValueError ("old_table and new_table must contain the same characters" )
# 创建一个空字典来存储位置关系
position_mapping = {}
# 遍历old_table来填充字典
for old_index, old_char in enumerate (old_table) :
new_index = new_table.index(old_char) # 获取old_char在new_table中的位置
position_mapping[old_index] = new_index
return position_mapping
def map_string(table, mapping):
"" "
根据给定的映射关系对字符串进行重新排列。
参数:
table (str): 需要映射的原始字符串。
mapping (dict): 位置关系的映射字典。
返回:
str: 映射后的字符串。
抛出:
ValueError: 如果table的长度和mapping的长度不同。
" ""
# 检查table的长度和mapping的长度是否相同
if len(table) != len(mapping):
raise ValueError("The length of the table and the length of the mapping must be the same" )
# 创建一个与原始字符串长度相同的列表,用于存放映射后的字符
mapped = [''] * len(table)
# 遍历原始字符串的每个字符和其对应的索引,按照映射关系将字符放到新的位置上
for original_index, char in enumerate(table):
new_index = mapping[original_index]
mapped[new_index] = char
# 将列表转换回字符串
mapped_string = ' '.join(mapped)
return mapped_string
# 创建位置替换表
old_table = "ABCDEF"
new_table = "BACFED"
position_mapping = create_position_mapping(old_table, new_table)
//print(position_mapping)
//{0: 1, 1: 0, 2: 2, 3: 5, 4: 4, 5: 3}
# 位置替换
table = "GHILMO"
mapped_table = map_string(table, position_mapping)
//print(mapped_table)
//HGIOML
值映射
s="BFDD"
old_table = "ABCDEF"
new_table = "GHIJKL"
#生成替换表
trans_table = str.maketrans(old_table, new_table)
# print(trans_table)
# {65 : 71 , 66 : 72 , 67 : 73 , 68 : 74 , 69 : 75 , 70 : 76 }
#替换函数
def translate_string(s, trans_table):
# 检查s中的字符是否都在trans_table的键中
for char in s:
if ord(char ) not in trans_table:
raise ValueError(f"Character {char} in string is not in the translation table" )
# 进行字符替换
return s.translate(trans_table)
result = translate_string(s,trans_table)
# print(result)
# HLJJ
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步