Input string elements in a tuple and replace all 'a' with 'an'. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Input string elements in a tuple and replace all 'a' with 'an'.

I have used the replace(). is there a different way to do the same without using the function? https://code.sololearn.com/cnAllnqbMyzQ/?ref=app

17th Nov 2019, 5:40 PM
Azmat
8 Answers
+ 12
Here a sample without using replace. Not as short as HonFu's solution... res = [] for i in seq: if i == 'a': res.append('an') else: res.append(i) print(''.join(res))
17th Nov 2019, 6:28 PM
Lothar
Lothar - avatar
+ 8
see some comments from me and also a reworked code: ''' seq= eval(input('enter elements \t')) # eval does not allow to evaluate strings, and should generally not be used because of security issues seq1= list(seq) # not necessary if you use replace() for index, item in enumerate(seq1): # not necessary to use loop if 'a' in item: #not necessary if you use replace() seq1[index] = item.replace('a','an') # use modified code here seq = tuple(seq1) # you don't need to a tuple print(seq) # -> the output is a bit weird... ''' # keep in mind, that both codes replace all *a*, wherever they appear # so the reworked code could be: seq = input('enter elements \t') # <----------- print(seq.replace('a','an'))
17th Nov 2019, 6:12 PM
Lothar
Lothar - avatar
+ 8
Azmat, you are using the *eval* function for input. This is very convenient in some cases. But eval also has a downside, as anything that will be input is executed. This can be a few numbers, but could also be some code that is malicious. So it's better to get around this, even if it's a bit more of coding. You can find here a really good article about using eval: https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice
18th Nov 2019, 7:10 AM
Lothar
Lothar - avatar
+ 5
print(*('an' if e=='a' else e for e in seq1)) Or in one line: print(*('an' if e=='a' else e for e in input().split())) (input like this: this is a line of input)
17th Nov 2019, 5:46 PM
HonFu
HonFu - avatar
18th Nov 2019, 8:17 AM
HonFu
HonFu - avatar
18th Nov 2019, 1:23 AM
Azmat
+ 2
HonFu Lothar thanks I understand now.
18th Nov 2019, 12:47 PM
Azmat
+ 1
Lothar I really can't wrap my head around why usage of 'eval' is discouraged can you explain it a bit? Thanks
18th Nov 2019, 1:26 AM
Azmat