简体   繁体   English

Python3:替换拆分的字符串

[英]Python3: Replace splitted string

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?有没有什么优雅的方法可以使用 python3 获得它?

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.如果您需要完全替换所有事件,而不管它们的位置如何,请查看此处的其他答案。

You can use the .replace() method:您可以使用.replace()方法:

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

You can use re.sub() from regex library.您可以使用正则表达式库中的 re.sub()。 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特点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM