0

I have string:

aStr = 'Name0, Location0, Address0, Price0'

I want to replace only ',' at position number2 by ' &'. I tried code below but its replace all ',' in my aString.

aStr = 'Name0, Location0, Address0, Price0'
print(aStr.replace(',', ' &'))  

How can I replace ',' at specific position?
I want output as below:

'Name0, Location0 & Address0, Price0'
PinkPanther
  • 35
  • 1
  • 8
  • try regex `re.sub(r'([^,]+,[^,]+)(?:,)(.*)', r'\1 &\2', aStr)` or `' '.join(aStr.split(',')[:2]) + ' &' + ' '.join(aStr.split(',')[2:])` obviously you can split it one time then use slice operator – Epsi95 Jul 07 '21 at 09:45

3 Answers3

1

For this specific case you can do :

aStr = 'Name0, Location0, Address0, Price0'
aStr = aStr.replace(',', ' &', 2)
aStr = aStr.replace('&', ',', 1)

You can use regex for a smooth and adaptable answer.

Youenn FS
  • 76
  • 2
1

First ao all find all position of the occurences of ',':

index = [pos for pos, char in enumerate(aStr) if char == ',']

Then replace the one you want (the second one):

aStr = aStr[:index[1]] + ' &' + aStr[index[1]+1:]
print(aStr)
>>>'Name0, Location0 & Address0, Price0'
zanga
  • 612
  • 4
  • 20
1

I read what you wanted to do well you just cant replace at specific index in python here is the code I did for you using slicing (concept). Well this code will only remove the first ',' in your string

aStr = 'Name0, Location0, Address0, Price0'
ind = aStr.index(',')
new_str = aStr[:ind] + aStr[ind+1:]
print(new_str)  
ashhad ullah
  • 116
  • 4