Python Forum
[SOLVED] Pad strings to always get three-digit number?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[SOLVED] Pad strings to always get three-digit number?
#1
Hello,

I've tried different things, but still can't strings to always be left-padded, three-digits long even for strings that contain a dash sign:

file1 = open('input.txt', 'r')
for line in file1.readlines():
  #print(line.zfill(3),end='') #001 expected, 01 returned :-/
  #print(line.zfill(4),end='') #doesn't work with range, eg. 30-42
  pass
Here's the source:
1
2
3
8-10
11
12-18
88-91
92-95
96-100
101-103
112-122
Thank you.
Reply
#2
Your description of the problem should include some examples. I assume that 1 should become 001 and 8 - 10 should become 008 - 010, but I could be wrong.

Your approach is wrong. You need to parse the file to find numbers, pad the numbers, and reconstruct the string. I would use re.sub() to find and replace the digit strings. You can read about it here:

https://docs.python.org/3/library/re.html
Reply
#3
Thank you.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [solved] a 4-digit display vr34 2 328 Apr-12-2024, 05:38 PM
Last Post: vr34
  Trying to understand strings and lists of strings Konstantin23 2 776 Aug-06-2023, 11:42 AM
Last Post: deanhystad
  Delete strings from a list to create a new only number list Dvdscot 8 1,554 May-01-2023, 09:06 PM
Last Post: deanhystad
  [SOLVED] [Windows] Fails reading strings with accents Winfried 1 842 Apr-23-2023, 05:27 PM
Last Post: Larz60+
  prefix ID Number with 0,00 make 3 digit. mg24 1 768 Oct-06-2022, 07:20 AM
Last Post: ibreeden
  Splitting strings in list of strings jesse68 3 1,780 Mar-02-2022, 05:15 PM
Last Post: DeaD_EyE
  Adding an ascending number [SOLVED] AlphaInc 3 2,255 Jul-11-2021, 10:13 AM
Last Post: perfringo
  [solved] Variable number of dictionnaries as argument in def() paul18fr 11 6,171 Apr-20-2021, 11:15 AM
Last Post: paul18fr
  if a string has a digit - print tester_V 2 2,155 Jan-16-2021, 04:48 AM
Last Post: tester_V
  Is this right code for 3 digit pin ? fatjuicypython 1 1,824 Aug-21-2020, 11:15 PM
Last Post: bowlofred

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020