python - Can someone explain why replace isn't working for me -


i need remove spaces in sentences. sentence "i  like   python" , need make "i python". used replace this:

>>> >>> sentence="i    python" >>> def checkio(element):         newelement=element.replace("  ", " ") , element.replace("   ", " ")         return newelement  >>> checkio(sentence) 'i  python' >>> 

and see, result "i  like python" though (think) told replace "  " " ". can clear me why didn't work?

this wanted do:

def checkio(element):     newelement = element.replace("  ", " ").replace("   ", " ")     return newelement 

you shorten

def checkio(element):     return element.replace("  ", " ").replace("   ", " ") 

however, if wanted replace arbitrary number of spaces? better split sentence on number of spaces, , join single space. this, use

def checkio(element):     return " ".join(element.split()) 

the split method takes string , separates list. no argument, separates on spaces:

>>> "i     python".split() ["i", "like", "python"] 

the join method takes list , makes string out of it, using string in between elements of list:

>>> ' '.join(["i", "like", "python"]) "i python" >>> '__help__'.join(["i", "like", "python"]) "i__help__like__help__python" 

why original attempt failed

the line

newelement = element.replace("  ", " ") , element.replace("   ", " ") 

was not doing expect because using "truthiness" of strings. and operator looks @ logical things. in python, strings except "" considered true. can use called "short-circuiting", did.

when use and, both left , right statement must true evaluate true. if left part false, there no reason move on right part , evaluation stops there (aka "short-circuiting"). if true, needs check right side see if whole statement true. can exploit fact return left statement if false, or right if left true:

>>> = "a" , "b" >>> "b" >>> = "" , "b" >>> "" >>> # works oppositely "or" >>> = "a" or "b" >>> "a" >>> = "" or "b" >>> "b" 

element.replace(" ", " ") returns string, , element.replace(" ", " "). since strings evaluate true, ever returning right statement of and.

this not common use of logical operatiors in python (it more used in other languages, though)


Comments

Popular posts from this blog

javascript - Unusual behaviour when drawing lots of images onto a large canvas -

how can i manage url using .htaccess in php? -

ios - I get the error Property '...' not found on object of type '...' -