15,880,299 members
See more:
I am trying to do a simple encoder in python that reads a string and if a number within that string is in between a "P" and "Y", it prints that string 2 times and if it is between small letters "p" and "y" it prints that string 3 times

for example the string P231313131Yp111111y, the output would be 231313131231313131111111111111111111.

the code I have written works for the most part but if the input is Pp123yYP221Y, the program gets stuck in a seemingly endless loop, where the expected output would be 123123123123123123221221

What I have tried:

Python
```string = "P231313131Yp111111y"
print("input: ", string)
marker1 = "P" and "Y"
marker2 = "p" and "y"
while marker1 in string:
if marker1 in string:
Number = (string[string.find("P")+1:string.find("Y")])
Numberwmarker = (string[string.find("P"):string.find("Y")+1])
output = Number * 2
string = string.replace(Numberwmarker, output, 1)
while marker2 in string:
if marker2 in string:
Number = (string[string.find("p")+1:string.find("y")])
Numberwmarker = (string[string.find("p"):string.find("y")+1])
output = Number * 3
string = string.replace(Numberwmarker, output, 1)
print("output:",string)```
Posted
Updated 31-May-22 22:10pm

## Solution 2

The expressions `marker1 = "P" and "Y"` and `marker2 = "p" and "y"` are not what you think. In essence they evaluate to the second value, so your while loops will most likely not do what you expect. See Built-in Types — Python 3.10.4 documentation[^].

## Solution 1

Your problem is that you are using two loops to process the data: You really want to use just one, and to heck with the replace function.

```1) Loop through once, looking at each character in turn.
1.1) If it's "P", set "expecting Y" and start building a new string.
1.2) If it's "p", set "expecting y" and start building a new string.
1.3) If you are "expecting Y" then
1.3.1) If it's "Y" then print the string you built twice, and clear "expecting Y". 1.3.2) Otherwise, add it to the building string.
1.4) If you are "expecting y" then
1.4.1) If it's "y" then print the string you built three times, and clear "expecting y". 1.4.2) Otherwise, add it to the building string.
1.4) Otherwise, print the character once.```

Try it on paper manually first, and you'll see what I mean!