I want to know why the code listed below is not functioning correctly.It should print 'Hi' but it is not printing it.Please look into this matter.Thanks in advance.
a=['{','}']
a=[(s.replace('{','H'),s.replace('}','i'))for s in a]
print(a)
I want to know why the code listed below is not functioning correctly.It should print 'Hi' but it is not printing it.Please look into this matter.Thanks in advance.
a=['{','}']
a=[(s.replace('{','H'),s.replace('}','i'))for s in a]
print(a)
Use the following:
a=['{','}']
a=[(s.replace('{','H').replace('}','i'))for s in a]
print(a)
Output:
['H', 'i']
It is working properly.
On the first element of the list, it encounters '{'
which is computed to 'H'
by s.replace('{','H')
although '{' remains the same by applying s.replace('}','i')
because the closing bracket ('}'
) is not encountered. Therefore, the result is ('H','{')
.
The same logic on the second element of the list.
You are doing two operations, comma-separated in brackets, which produces two values, called a tuple (one result for each replace operation). Here's how to do what you want:
[s.replace('}','i').replace('{','H') for s in a]
There are couple of things to being with. 1. You are trying to return a tuple and not a string, so 'Hi' is not possible. You would get '[('H', '{'), ('}', 'i')]'. 2. For string try below code. You should try replace on the list that is already replaced and then extract string out of it.
a=['{','}']
a=[s.replace('{', "H") for s in a]
a=[s.replace('}',"i") for s in a]
print("".join(a))
below is the single line code with same result.
a=['{','}']
print("".join([s.replace('{', "H").replace("}", "i") for s in a]))