0

I am writing a file which gets information about stock items from a csv, the issue is that most of the stock item IDs are 4 digits long, but some of them are 2 or 3 digits, and the remaining digits are replaced with apostrophes ( 872' or 99'' for example). Because the user can pass in specific stock item IDs it would be better if they did not have to include apostrophes in their input just so the code runs, so I want to append apostrophes to their input ID.

At the moment, the stock item IDs to get information for are retrieved using this code::

if args.ID:
    if args.ID[0].endswith('.txt'):
        with open(args.ID[0], 'r') as f:
            IDs = [line for line in f]
    else:
        IDs = args.FTID
else:
    IDs = [ID[25:29] for ID in df['Stock Items'].unique()]

Then I iterate through the dataframe:

for index, row in df.iterrows():
    if row['Stock Items'][25:29] in FTIDs:
         # Processing

I need to be able to make sure that any input IDs are in the format above.

  • 2
    Use `ljust` (obviously with `"'"` as fill character, not space): [How can I fill out a Python string with spaces?](https://stackoverflow.com/questions/5676646/how-can-i-fill-out-a-python-string-with-spaces) – mkrieger1 Jul 29 '20 at 08:39
  • Yes it does, thank you –  Jul 29 '20 at 08:56

1 Answers1

-1

If you have str and you are 100% sure it is not longer than 4, you can use .ljust to get str with required number of ' added following way

myid = "99"
formatted_id = myid.ljust(4, "'")
print(formatted_id)

Output:

99''
Daweo
  • 10,139
  • 2
  • 5
  • 10