-1

I try to add "G:" in the beginning and a backslash before every point of each element in a list. Therefore I created this example list1:

list1 = ['AEX.EN', 'AXAL.OQ', 'AAPIOE.NW']

And I need something like list2:

list2 = ['G:AEX\.EN', 'G:AXAL\.OQ', 'G:AAPIOE\.NW']

Thank you very much for the help!

fjurt
  • 783
  • 3
  • 14

2 Answers2

1

Use:

>>> ['G:' + i.replace('.', '\\.') for i in list1]
['G:AEX\\.EN', 'G:AXAL\\.OQ', 'G:AAPIOE\\.NW']
>>> 

In this case I prefer re.escape:

>>> import re
>>> ['G:' + re.escape(i) for i in list1]
['G:AEX\\.EN', 'G:AXAL\\.OQ', 'G:AAPIOE\\.NW']
>>> 
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
1

You can use + for join string then use replace() like below:

>>> list1 = ['AEX.EN', 'AXAL.OQ', 'AAPIOE.NW']

>>> [('G:'+l).replace('.','\.') for l in list1]
['G:AEX\\.EN', 'G:AXAL\\.OQ', 'G:AAPIOE\\.NW']
I'mahdi
  • 23,382
  • 5
  • 22
  • 30
  • > list2 = ['G:AEX\.EN', 'G:AXAL\.OQ', 'G:AAPIOE\.NW'] >print(list2) > OUTPUT: ['G:AEX\\.EN', 'G:AXAL\\.OQ', 'G:AAPIOE\\.NW'] for i in list2: print(i) > OUTPUT: G:AEX\.EN G:AXAL\.OQ G:AAPIOE\.NW Why this is happening? – ujjwal_bansal Oct 26 '21 at 15:44
  • @ujjwal_bansal this happen in python, you can read [here](https://stackoverflow.com/questions/6477823/display-special-characters-when-using-print-statement) or [here](https://stackoverflow.com/questions/32491682/how-to-print-in-python) – I'mahdi Oct 26 '21 at 16:39