如何在Python中按位互斥或两个字符串? [英] how to do bitwise exclusive or of two strings in python?

查看:65
本文介绍了如何在Python中按位互斥或两个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在python中执行按位异或两个字符串,但是python中不允许对字符串进行异或.我该怎么办?

I would like to perform a bitwise exclusive or of two strings in python, but xor of strings are not allowed in python. How can I do it ?

推荐答案

您可以将字符转换为整数,然后将其转换为xor:

You can convert the characters to integers and xor those instead:

l = [ord(a) ^ ord(b) for a,b in zip(s1,s2)]

这是一个更新的函数,以防因XOR而需要一个字符串:

Here's an updated function in case you need a string as a result of the XOR:

def sxor(s1,s2):    
    # convert strings to a list of character pair tuples
    # go through each tuple, converting them to ASCII code (ord)
    # perform exclusive or on the ASCII code
    # then convert the result back to ASCII (chr)
    # merge the resulting array of characters as a string
    return ''.join(chr(ord(a) ^ ord(b)) for a,b in zip(s1,s2))

查看其在线运行情况: ideone

See it working online: ideone

这篇关于如何在Python中按位互斥或两个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆