0

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)
Ra143
  • 13
  • 3

4 Answers4

3

Use the following:

a=['{','}']
a=[(s.replace('{','H').replace('}','i'))for s in a]
print(a)

Output:

['H', 'i']
Code Pope
  • 5,075
  • 8
  • 26
  • 68
0

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.

nprime496
  • 66
  • 2
  • 6
0

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]
pink spikyhairman
  • 2,391
  • 1
  • 16
  • 13
0

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]))