Python Forum

Full Version: zfill prints extra et the end of a var
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Greetings to you all!
I'm trying to replace single digits at the beginning of each string in a files
The integers are always in the range of 1-12.
Here is a test file:
1,xxx,ddd-02,cc1,
2,xxx,ddd-02,cc1,
3,xxx,ddd-02,cc1,
10,xxx,ddd-02,cc1,
11,xxx,ddd-02,cc1
12,xxx,ddd-02,cc1,
Here is a snippet:

with open(fls) as blt_orig :
    for el in blt_orig :
        el.strip()
        num,*gb = el.split(",")
        new_n = num.zfill(2)     # <-- Adding a zero to the number      
        nln =re.sub("\d|\d{2}",new_n,el,count=1)  # <-- replacing the digits in the string with the new one  
        print(f"{nln}")
And a strange printout:

01,xxx,ddd-02,cc1,

02,xxx,ddd-02,cc1,

03,xxx,ddd-02,cc1,

100,xxx,ddd-02,cc1,

111,xxx,ddd-02,cc1

122,xxx,ddd-02,cc1,
For some reason, it prints extra digits to the 10/11 and 12.
Thank you.
The probelm is in the re.sub which says "replace one or two digits in el with new_n. When el starts with 2 digits, both 1 digit and two digits match, and the first match wins. If you write the regex like this it works:
nln = re.sub("\d{2}|\d", new_n, el, count=1)
Now it says "replace two digits or one digit witn new_n.

That works, but it is an odd way to solve the problem. You want to get the numeric prefix, and the rest of the string. You then want to pad the prefix length 2 and concatenate. I would not use regex or zfill.
with open("input.txt") as f:
    for line in f:
        prefix, suffix = line.strip().split(",", maxsplit=1)
        print(f"{prefix:>02},{suffix}")
Dear God!
I have never seen it before:
prefix, suffix = line.strip().split(",", maxsplit=1)
prefix and suffix...
I need to find info on that.
Thank you!
prefix and suffix are just variables. They could be a and b or they could be num_str and leftover. Nothing special about prefix and suffix other than being good choices for variable names. There is no magic here. Nothing new. Just using split() to split a string into two strings. The split character is the first comma. Since there are more than one comma, I set the maxsplit to 1. This will give me the string before the first comma (prefix) and the string after the first comma (suffix).
Thank you for sharing! I did not know that!
I'll call you 'deanhystad the good one!' Smile