-3

This is my string:

VISA1240129006|36283354A|081016860665

I need to replace first string.

FIXED_REPLACED_STRING|36283354A|081016860665

I mean, I for example, I need to get next string:

Is there any elegant way to get it using python3?

khelwood
  • 52,115
  • 13
  • 74
  • 94
Jordi
  • 18,082
  • 29
  • 125
  • 263

3 Answers3

3

You can do this way:

>>> l = 'VISA1240129006|36283354A|081016860665'.split('|')
>>> l[0] = 'FIXED_REPLACED_STRING'
>>> l
['FIXED_REPLACED_STRING', '36283354A', '081016860665']
>>> '|'.join(l)
'FIXED_REPLACED_STRING|36283354A|081016860665'

Explanation: first, you split a string into a list. Then, you change what you need in the position(s) you want. Finally, you rebuild the string from such a modified list.

If you need a complete replacement of all the occurrences regardless of their position, check out also the other answers here.

floatingpurr
  • 6,509
  • 7
  • 39
  • 88
1

You can use the .replace() method:

l="VISA1240129006|36283354A|081016860665" 
l=l.replace("VISA1240129006","FIXED_REPLACED_STRING")
NicolasPeruchot
  • 374
  • 2
  • 8
  • 1
    This is even better if you do not need to deal with "positional" replacement (ie. change exactly the _n-th_ string in pipe-separeted values). I mean, `replace` changes all the occurrences matching the filter. It depends on the OP needs. – floatingpurr Nov 11 '21 at 09:46
0

You can use re.sub() from regex library. See similar problem with yours. replace string

My solution using regex is:

import re
l="VISA1240129006|36283354A|081016860665"
new_l = re.sub('^(\w+|)',r'FIXED_REPLACED_STRING',l)

It replaces first string before "|" character

12kadir12
  • 108
  • 8