简体   繁体   中英

bitwise operation inside the string in python

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

How to perform the operation in s if s is a string in python?

my problem is to replace a with bitwise and, b with bitwise or, and c with bitwise or and perform the action.

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.

Python's eval() is an incredibly useful tool, the function has some important security implications that you should consider before using it. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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