2 回答

TA貢獻1797條經驗 獲得超4個贊
使用
^([^,]*),|,(?=[^,]*$)
替換為\1||
.?見證明。
解釋
--------------------------------------------------------------------------------
? ^? ? ? ? ? ? ? ? ? ? ? ? the beginning of the string
--------------------------------------------------------------------------------
? (? ? ? ? ? ? ? ? ? ? ? ? group and capture to \1:
--------------------------------------------------------------------------------
? ? [^,]*? ? ? ? ? ? ? ? ? ? any character except: ',' (0 or more
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?times (matching the most amount
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?possible))
--------------------------------------------------------------------------------
? )? ? ? ? ? ? ? ? ? ? ? ? end of \1
--------------------------------------------------------------------------------
? ,? ? ? ? ? ? ? ? ? ? ? ? ','
--------------------------------------------------------------------------------
?|? ? ? ? ? ? ? ? ? ? ? ? OR
--------------------------------------------------------------------------------
? ,? ? ? ? ? ? ? ? ? ? ? ? ','
--------------------------------------------------------------------------------
? (?=? ? ? ? ? ? ? ? ? ? ? look ahead to see if there is:
--------------------------------------------------------------------------------
? ? [^,]*? ? ? ? ? ? ? ? ? ? any character except: ',' (0 or more
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?times (matching the most amount
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?possible))
--------------------------------------------------------------------------------
? ? $? ? ? ? ? ? ? ? ? ? ? ? before an optional \n, and the end of
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?the string
--------------------------------------------------------------------------------
? )? ? ? ? ? ? ? ? ? ? ? ? end of look-ahead
import re
regex = r'^([^,]*),|,(?=[^,]*$)'
test_str = r'101, "Name1", "Designation1", "blah1", "Blah1", 20200914001'
subst = r'\1||'
print(re.sub(regex, subst, test_str))
結果:101|| "Name1", "Designation1", "blah1", "Blah1"|| 20200914001.

TA貢獻1906條經驗 獲得超10個贊
您可以拆分第一個(maxsplit=1從左起)和最后一個(maxsplit=1從右起)逗號并連接結果,例如:
>>> line = '101, "Name1", "Designation1", "blah1", "Blah1", 20200914001'
>>> first, rest = line.split(',', maxsplit=1)
>>> rest, last = rest.rsplit(',', maxsplit=1)
>>> '||'.join((first, rest, last))
'101|| "Name1", "Designation1", "blah1", "Blah1"|| 20200914001'
添加回答
舉報