Splitting a string in a list to find and replace elements in python

  • A+
Category:Languages

I have a list of currency pairs, let's say for example it looks like this:

cp = ['EURUSD', 'CHFUSD', 'JPYUSD', 'CADUSD'] 

What I'm looking to do is iterate through this list, changing the USD to GBP to result in a new list that would display:

new_cp = ['EURGBP', 'CHFGBP', 'JPYGBP', 'CADGBP'] 

The way I assumed I would do it would be to loop through each pair, split the string into a list, remove the last 3 elements, and then append 'G', 'B', 'P' as the new last 3 elements, and finally returning this back in to a string, and adding it to the new list, 'new_cp'.

The code I began with was:

for pair in cp:    split_pair = pair.split() 

However, all this results in is getting:

['EURUSD'] ['CHFUSD'] 

etc.

So it's just splitting the list, not splitting the string for each currency pair within the list.

I know this is relatively beginner stuff, but I am really stumped. I just don't get why this doesn't work.

If you can help with what I am doing wrong there, or even suggest a more efficient way to achieve what I'm looking to do that would be really appreciated.

 


I would suggest using the .replace() method

For example:

cp = ['EURUSD', 'CHFUSD', 'JPYUSD', 'CADUSD'] new_cp = []  for currency in cp:     new_cp.append(currency.replace('USD', 'GBP'))  print(new_cp)  >> ['EURGBP', 'CHFGBP', 'JPYGBP', 'CADGBP'] 

Hope this helps :)

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: