I'm brand new and been going through some beginner code problems on checkIO. I finished this one today and am posting because I'm sure there is a much more elegant way to accomplish this, and I think this particular problem has a lot of useful applications. I would like to know what are the 'clean and efficient' ways to do it, or maybe what built-ins I haven't learned yet that I should explore. My version seems pretty ugly. Thanks!
Problem: take a tuple of phrases, anytime the word 'right' appears, replace it with 'left'. Create a new string combining all the phrases separated with a comma.
def left_join(phrases):
"""
Join strings and replace "right" to "left"
"""
phrases = list(phrases)
newstr = ''
for j, phrase in enumerate(phrases):
if 'right' in phrase:
mod = dict(enumerate(phrase))
for key in mod:
if mod[key] == 'r' and mod[key+4] == 't':
i = key
mod[i] = 'l'
mod[i+1] = 'e'
mod[i+2] = 'f'
mod[i+3] = 't'
mod[i+4] = ''
switch = (list(mod.values()))
phrase = ''.join(switch)
if j == (len(phrases) - 1) or len(phrases) == 1:
newstr += phrase
else:
newstr += phrase + ','
else:
if j == (len(phrases) - 1) or len(phrases) == 1:
newstr += phrase
else:
newstr += phrase + ','
return newstr
test1 = ("bright aright", "ok", "brightness wright",)
test2 = ("lorem","ipsum","dolor", "fright", "nec","pellentesque","eu",
"pretium","quis","sem","nulla","consequat","massa","quis",)
r
and ends witht
that is not the word right, it would modify that too. That's not good. What did you see about the test("crash",)
? \$\endgroup\$KeyError: 10
. Originally, I had a break statement so it would pop out after it found the word, but then it would miss another instance of 'right' in the phrase if there was one. I'm going to play around with a fix. \$\endgroup\$try
statement after for key and before theif
statement:try: mod[key] == 'r' and mod[key+4] == 't' except KeyError: break
\$\endgroup\$