-1
for i in range(len(p)):
    x = ""
    if (p[i] == "1") or (q[i] == "1"):
      x[i] = 1
    else:
      x[i] = 0

I have this so far. I basically just want to know how to concatenate onto the string x to add more bits since python strings are immutable. I barely started using python or i would explain myself better

Jab
  • 26,853
  • 21
  • 75
  • 114
  • Every iteration you make `x` a blank string – Jab Sep 08 '20 at 23:16
  • What are `p` and `q`? And what is expected output? – Jab Sep 08 '20 at 23:16
  • p and q are bits so "1101" and "1001" respectively. The output should be another string of bits so "1101" for example – WeepingWillow Sep 08 '20 at 23:18
  • String concatenation is demonstrated in any tutorial on Python strings. Where are you having trouble? – Prune Sep 08 '20 at 23:21
  • @WeepingWillow -- hey, sorry to address you via a comment on an unrelated post, but I can't reach you otherwise since you deleted the other question so it's no longer able to be commented on. See https://gist.github.com/charles-dyfis-net/a4dc8b9c8f52c7201b0e1b1344939e55 for an example of how to shorten your logic-gate demo code. – Charles Duffy Sep 17 '20 at 21:52

3 Answers3

0

This should work:

x = ""
for i in range(len(p)):
    if (p[i] == "1") or (q[i] == "1"):
      x += "1"
    else:
      x += "0"

Keep in mind I think iterating on both at the same time and using a list would be better:

x = []
for i, j in zip(p, q):
    if i == "1" or j == "1":
        x.append("1")
    else:
        x.append("0")
x = "".join(x)
Bharel
  • 23,672
  • 5
  • 40
  • 80
  • Okay this makes sense. I've never used zip. I basically have 0 python experience so I was using my knowledge of other languages. – WeepingWillow Sep 08 '20 at 23:29
0

Why not just use str.join and a comprehension. Also just loop through each string simultaneously using zip:

''.join('1' if '1' in g else '0' for g in zip(p, q))
Jab
  • 26,853
  • 21
  • 75
  • 114
0

1- Create a list with length of P, that contain only "0" elements
2- Work with this list to change the element at the corresponding index
3- At the end, join the element of the list to get one string

p = "11100011"
q = "00000011"

list_x = ["0"]*len(p)

for i in range(len(p)):
    if (p[i] == "1") or (q[i] == "1"):
      list_x[i] = "1"

str = "".join(list_x)

print (str)

it gives you

11100011

for more details:

An important point here is the index i, this method work independently where you start the strings (from beginning or the end or at any point).
If you want to start from the beginning of the string, so you can use the solution proposed by others (@Bharel and @Jab).

x = ""
for i in range(len(p)):
    if (p[i] == "1") or (q[i] == "1"):
      x += "1"
    else:
      x += "0"
ibra
  • 1,164
  • 1
  • 11
  • 26