简体   繁体   English

python 中的字符串内的按位运算

[英]bitwise operation inside the string in python

s = "1 ^ 0 ^ 1 ^ 1 & 0 | 1 " s = "1 ^ 0 ^ 1 ^ 1 & 0 | 1 "

How to perform the operation in s if s is a string in python?如果 s 是 python 中的字符串,如何执行 s 中的操作?

my problem is to replace a with bitwise and, b with bitwise or, and c with bitwise or and perform the action.我的问题是用按位替换 a ,用按位或替换 b ,用按位或替换 c 并执行操作。

k = '1C0C1C1A0B1'
alpha = []
for i in range(len(k)):
    p = k[i]
    alpha.append(p)

for i in range(len(alpha)):
    if alpha[i] == 'A':
        alpha[i] = '&'
    if alpha[i] == 'B':
        alpha[i] = '|'
    if alpha[i] == 'C':
        alpha[i] = '^'

s = " ".join(map(str, alpha))
print(s)

i tried this above code i don't know how to proceed further.我尝试了上面的代码,我不知道如何进一步进行。 Please help me.请帮我。

You can use eval command.您可以使用 eval 命令。

Python's eval() is an incredibly useful tool, the function has some important security implications that you should consider before using it. Python 的 eval() 是一个非常有用的工具,function 具有一些重要的安全隐患,您应该在使用它之前考虑这些问题。 https://realpython.com/python-eval-function/ https://realpython.com/python-eval-function/

k = '1C0C1C1A0B1'
s = k.replace('A', '&').replace('B', '|').replace('C','^')
eval(s)
# output : 1

security checking with regex使用正则表达式进行安全检查

import re
regex = r"^((0|1)[A-C])*(0|1)$"
k = '1C0C1C1A0B1'

# Input control
match = re.match(regex, k)
if not match:
    raise Exception("Input format error") 


s = k.replace('A', '&').replace('B', '|').replace('C','^')
eval(s)
# output : 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM