Reputation: 479
I have this string:
abc,12345,abc,abc,abc,abc,12345,98765443,xyz,zyx,123
What can I use to add a 0
to the beginning of each number in this string? So how can I turn that string into something like:
abc,012345,abc,abc,abc,abc,012345,098765443,xyz,zyx,0123
I've tried playing around with Regex but I'm unsure how I can use that effectively to yield the result I want. I need it to match with a string of numbers rather than a positive integer, but with only numbers in the string, so not something like:
1234abc567
into 01234abc567
as it has letters in it. Each value is always separated by a comma.
Upvotes: 0
Views: 82
Reputation: 660
If the numbers are always seperated by commas in your string, you can use basic list methods to achieve the result you want.
Let's say your string is called x
y=x.split(',')
x=''
for i in y:
if i.isdigit():
i='0'+i
x=x+i+','
What this piece of code does is the following: Splits your string into pieces depending on where you have commas and returns a list of the pieces. Checks if the pieces are actually numbers, and if they are a 0 is added using string concatenation. Finally your string is rebuilt by concatenating the pieces along with the commas.
Upvotes: 1
Reputation: 174696
Use re.sub
,
re.sub(r'(^|,)(\d)', r'\g<1>0\2', s)
or
re.sub(r'(^|,)(?=\d)', r'\g<1>0', s)
or
re.sub(r'\b(\d)', r'0\1', s)
Upvotes: 1