For the robber's language challenge thing Wikipedia I struggled with my limited knowledge and came up with this:
def translate(txt):
new_txt = ''
consonants = 'bcdfghjklmnpqrstvwxz'
for x in txt:
if x in consonants:
new_txt += x + 'o' + x
else:
new_txt += x
return new_txt
print(translate("Hello World"))
I understand the += operator works to append the new_txt variable, versus using just =, which would result in an answer of just "dod" in this example as it replaces everything each cycle of the for loop leaving the last run when x == d. I found several pithier solutions to the problem, however my experience with both Python and coding in general is lacking, and I can't understand several aspects of these answers. For example:
def translate(txt):
consonants = 'bcdfghjklmnpqrstvwxz'
new_txt = (x + 'o' + x if x in consonants else x for x in txt)
return ''.join(new_txt)
print(translate("Hello World"))
which is provided with varying levels of similarity in a few threads by several users, however I don't understand how this
new_txt = (x + 'o' + x if x in consonants else x for x in txt)
return ''.join(new_txt)
part differs from what I came up with. What type of component is this, and how does it do the job of the += on the new_txt string and append the result of each subsequent cycle of the
new_txt = (x + 'o' + x if x in consonants else x for x in txt)
line? What gives the result of that statement persistence, i.e. why isn't it replaced for each cycle and character of the entered txt string? What is this concept called? I have looked online and in StackOverflow, but it's difficult because I don't know what I'm looking for as someone very new to coding. I have a feeling that it's something very fundamental and I should know the answer in order to attempt something like this, however at this point, if I don't ask I won't know. Thank you.