0

This program produces a service key based on the current month and the store number. The last four numbers of the variable "key" is the key. Depending on the month and the store number the result may be four digits or it may be more. I just need to print out the last four digits of the variable "key" weather its four digits or forty. Not sure what to do from here

from datetime import datetime

now = datetime.now() # current date and time

def main():  
    month = now.strftime("%m")
    month = int(month)
    store = input("What is the four digit store number? ")
    storen = store[::-1]
    storenn = int(storen)
    value1 = storenn + month
    value2 = value1 * month
    value3 = str(value2)
    value4 = value3.split()
    value5 = str(value4)
    key = value5[4:-1]

    print(key)


main()
Fat_Rat_800xl
  • 21
  • 1
  • 3

2 Answers2

0

To answer the question you asked, change key = value5[4:-1] to key = value5[-4:]

As a commenter noted, Python's list slicing is a powerful tool, though potentially confusing if you're not already familiar with it. Here's a SO answer that may help understand how to use it.


If I may ask, what is your code doing? Does the below do what you want? (It's intended to be a simplified version of your code.)


from datetime import datetime

now = datetime.now() # current date and time

def main():
    # instead of string-formatting the month
    # and then converting to an int, use the .month property directly
    month = now.month

    # do the reversing and int-casting in one pass
    store = int(input("What is the four digit store number? ")[::-1])
    
    # do the value manipulation in one pass
    value = (store + month) * month

    # extract the key as the last 4 characters of the value as a str
    key = str(value)[-4:]
    
    # better to return a value from a function, than to print it
    return key

print(main())

which gives

What is the four digit store number? 4056
1665

though, if you're trying to make a collision-resistant hash of your store number, this method is suspect.

Joshua Voskamp
  • 1,855
  • 1
  • 10
  • 13
0

The last character of a string has index position -1. So, to get the last 4 characters from a string, pass -4 in the square brackets i.e.

# Get last character of string i.e. char at index position -1
test = "123456"
last_char = test[-4:]
print('Last character : ', last_char)
Jean Camargo
  • 340
  • 3
  • 17