top bantz
top bantz

Reputation: 615

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

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.

Upvotes: 1

Views: 2860

Answers (4)

Sivaraj Velayutham
Sivaraj Velayutham

Reputation: 187

Here is another solution. You can use RegEx to replace the Currency values.

import re

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

mycurr = 'GBP'

to_curr = re.compile("USD")

for pair in cp:
    print(to_curr.sub(mycurr, pair))

Output:

EURGBP
CHFGBP
JPYGBP
CADGBP

Upvotes: 2

Joe Tilsed
Joe Tilsed

Reputation: 324

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

Upvotes: 5

Luke DeLuccia
Luke DeLuccia

Reputation: 541

If you know that each currency pair will contain USD as the last three characters, the more efficient way is to just use list indexing and append GBP:

new_cp = [i[:-3] + 'GBP' for i in cp]

Upvotes: 3

user5407570
user5407570

Reputation:

You could achieve this by using replace in a list comprehension:

cp = ['EURUSD', 'CHFUSD', 'JPYUSD', 'CADUSD']
new_cp = [word.replace('USD', 'GBP') for word in cp] 
#i.e.: for word in cp, we apply the specified function to it - replace the 'USD' in that word with 'GBP' - and then append it to a new list
print(new_cp)

outputs: ['EURGBP', 'CHFGBP', 'JPYGBP', 'CADGBP']

Upvotes: 4

Related Questions