2

I need to format my code in such a way that i can input a year and quarter number into my function below. The link has to be in byte format for later on in the code. The code itself comes from 2.7 which is why it is not working properly right now and gives the 'bytes' object has no attribute 'format' error. I know bytes do not have the .format attribute, but I have been unable to find another way to interpolate the function below. Can somebody help me?

def get_index(year, qtr, ftype):

    url = b"https://www.sec.gov/Archives/edgar/full-index/{0}/QTR{1}/master.idx".format(year, qtr) #Master index from year and quarter

Paul Floyd
  • 5,530
  • 5
  • 29
  • 43
Ralf Ralfsen
  • 31
  • 1
  • 2
  • Is there a reason it has to be bytes, and not a plain string? – John Gordon May 12 '20 at 21:40
  • I will leave this link here because it is the same error that python 3 throws and the way to encode the string are different. Maybe this will save a couple misguided devs a few minutes [Best way to convert string to bytes in Python 3?](https://stackoverflow.com/a/7585619/3154857) – Gilberto Treviño Apr 07 '21 at 21:05

2 Answers2

3

Use a plain string to get the desired formatting, then call bytes() afterward:

url = "https://www.sec.gov/Archives/edgar/full-index/{0}/QTR{1}/master.idx".format(year, qtr)
url = bytes(url)
John Gordon
  • 29,573
  • 7
  • 33
  • 58
2

Use format in on a simple string then while converting the string to bytes specify the encoded format as 'utf8'.

bytes('https://www.sec.gov/Archives/edgar/full-index/{0}/QTR{1}/master.idx'.format(year, qtr),
encoding='utf8')
imankalyan
  • 155
  • 1
  • 8