-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?

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use the .replace() method:

l="VISA1240129006|36283354A|081016860665" 
l=l.replace("VISA1240129006","FIXED_REPLACED_STRING")

1 Comment

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.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.