-4

I am beginner in python i wanna add a substring in my python code. Here is my code

def gen_qr_text(acc_id,amount):
pp_acc_id = ""
pp_amount = ""
pp_chksum = ""

if len(acc_id) == 15:
  pp_acc_id = "0315" + acc_id
elif len(acc_id) == 13:
  pp_acc_id = "0213" + acc_id
elif len(acc_id) == 10:
  pp_acc_id = "01130066" + acc_id.substring(1)
else:
  return "null"

if not amount:
  pp_amount = str.format("54%02d%s", len(amount), amount)

pp_str = "00020101021129370016A000000677010111" + pp_acc_id + "5303764" +          pp_amount + "5802TH" + "6304"

pp_chksum = str(crc(pp_str))
pp_str += pp_chksum
return pp_str 

It makes some error in my code. Here is the line:

pp_acc_id = "01130066" + acc_id.substring(1)

i wanna update to add substring. I converted this code from java. What should i do to convert this line in python.

2 Answers2

0

You can conceptually access parts of a string as iterable list of chars:

mystring = "this is a string"

print mystring[0]   # will print "t"
print mystring[1:]  # will print "his is a string"
print mystring[::2] # will print "ti sasrn" (every other character)

For more information about list comprehensions look into your python api or search SO - f.e. explanation-of-how-list-comprehension-works or is-there-a-way-to-substring-a-string-in-python

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

This is what you're looking for:

def gen_qr_text(acc_id,amount):
    pp_acc_id = ""
    pp_amount = ""
    pp_chksum = ""

    if len(acc_id) == 15:
        pp_acc_id = "0315" + acc_id
    elif len(acc_id) == 13:
        pp_acc_id = "0213" + acc_id
    elif len(acc_id) == 10:
        pp_acc_id = "01130066" + acc_id[1]
    else:
        return None

    if not amount:
        pp_amount = "54{:2d}{}".format(len(amount), amount))

    pp_str = "00020101021129370016A000000677010111" + pp_acc_id + "5303764" +          pp_amount + "5802TH" + "6304"

    pp_chksum = str(crc(pp_str))
    pp_str += pp_chksum
    return pp_str 

Also note that there's nothing called null in Python, return None.

unixia
  • 4,102
  • 1
  • 19
  • 23
  • Thank you so much. I convert this line java to python, in java it's: [if !=amount.isEmpty(): pp_amount = String.format("54%02d%s", amount.length(), amount)] in python it's: [if not amount: pp_amount = str.format("54%02d%s", len(amount), amount)]. Is that okey? In my code its line 15 – user7657378 Nov 17 '17 at 13:40
  • Edited. Please check. – unixia Nov 17 '17 at 13:47
  • So, i don't need to write string when i will convert my code in python? – user7657378 Nov 17 '17 at 13:53
  • If the data type of amount is integer then you'll have to use `pp_amount = "54{:2d}{}".format(str(len(amount)), str(amount)))` – unixia Nov 17 '17 at 13:55