CAVS CAVS - 19 days ago 5
Python Question

Print every character in a string before a specific character

phrase='!_#@%'
pun=''
string='dj_khaled'
for item in string:
if item not in phrase:
pun=pun+item
print(pun)


My problem is that, the outpout i get is djkhaled instead it should be dj, So basically, i want to include every character before some symbol occurs. The string is alphanumberic.

Answer

Your loop adds to pun whenever a character is not in phrase, instead you should check if a character is in phrase and break accordingly. Until then you continuously add characters to pun:

for item in string:
    if item in phrase:
        break
    pun += item

When executed it now prints out correctly "dj".

You could also consider takewhile from itertools if the previous approach doesn't suffice:

>>> "".join(takewhile(lambda x: x not in phrase, string))
"dj"

Yet another approach that doesn't use a break(?) could be by using a boolean flag that indicates whether the value in the phrase was seen, you can then act on that when deciding if you should add to pun or not:

phrase='!_#@%'
pun=''
string='dj!khaled'
seen = False
for item in string:
    if item in phrase:
       seen = True
    if not seen:
        pun += item
print(pun)