Home:ALL Converter>Print every character in a string before a specific character

Print every character in a string before a specific character

Ask Time:2016-11-20T08:27:42         Author:Monty

Json Formatter

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.

Author:Monty,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/40699401/print-every-character-in-a-string-before-a-specific-character
Dimitris Fasarakis Hilliard :

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:\n\nfor item in string:\n if item in phrase:\n break\n pun += item\n\n\nWhen executed it now prints out correctly \"dj\".\n\nYou could also consider takewhile from itertools if the previous approach doesn't suffice:\n\n>>> \"\".join(takewhile(lambda x: x not in phrase, string))\n\"dj\"\n\n\nYet 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:\n\nphrase='!_#@%'\npun=''\nstring='dj!khaled'\nseen = False\nfor item in string:\n if item in phrase:\n seen = True\n if not seen:\n pun += item\nprint(pun)\n",
2016-11-20T00:32:32
jeremycg :

You can do this more easily using indexing with the index method:\n\npun = string[:string.index(phrase)]\nprint(pun)\n\n\nif we have multiple 'phrases', and some may not be in the string:\n\nphrase=['_','j','z']\n\npun = string[:min([string.index(i) for i in phrase if i in string])]\nprint(pun)\n",
2016-11-20T00:39:13
yy