Search code examples
pythonpython-3.xreview

Can I get a code review? Need help if I could have done this more efficient


I am new here and new to coding with python. I recently started an online coarse and wanted to see if there was an easier way that I could have created a 12 digit random hex list. I wanted each individual bit to be a random number or letter either lowercase or uppercase. Based on my rookie research this was the best I could find and created my own code.. so could I have done this a lot simpler and efficient?

#!/user/bin/python
import string
import random 

r1 = random.choice(string.hexdigits)
r2 = random.choice(string.hexdigits) 
r3 = random.choice(string.hexdigits)  
r4 = random.choice(string.hexdigits) 
r5 = random.choice(string.hexdigits)
r6 = random.choice(string.hexdigits)
r7 = random.choice(string.hexdigits)
r8 = random.choice(string.hexdigits)
r9 = random.choice(string.hexdigits)
r10 = random.choice(string.hexdigits)
r11 = random.choice(string.hexdigits)
r12 = random.choice(string.hexdigits)

randnumb = r1+r2+":"+r3+r4+":"+r5+r6+":"+r7+r8+":"+r9+r10+":"+r11+r12

print(randnumb)

Solution

  • You can use a loop with str.join():

    from random import choice
    from string import hexdigits
    
    print(":".join(choice(hexdigits) + choice(hexdigits) for _ in range(6)))
    # 47:8b:FA:71:90:ea
    

    Which combines two random hex digits 6 times, equivalent to your 12 separate calls.

    Or as @Jon Clements suggests in the comments:

    ':'.join(format(choice(range(256)), 'x') for _ in range(6))
    

    Which uses Hex format 'x' with format() across all 256 ASCII characters.

    Additionally, to be super safe you can pad format to 2 characters with 02x/02X:

    format(choice(range(256)), '02x') # lowercase padding
    format(choice(range(256)), '02X') # uppercase padding
    

    x is lower-case hexadecimal and X is upper-case hexidecimal. It's good to be consistent here to avoid strange lowercase and uppercase mixings. One example of this consistency is MAC addresses, where the hexidecimal strings are only in lowercase.

    You can read more about this and its variations in the Format Specification Mini-Language.

    Another thing you can do is replace choice(range(256)) with random.randrange(256), avoiding the need to use range().