Search code examples
pythonrandomgenerator

How do I exclude the first character if its 0 from a string in python (in a randomly generated string)


So I'm new to this site, and I'm trying to solve something in my code. I'm trying to make a lightshot screenshot scraper in python, but I've found out any code that starts with 0 will redirect to the home page, and would like to avoid that. My current code and an example output:

import string
import random
def main():
  def gen(x):
    N = 6
    r = ''.join(random.choices(string.ascii_lowercase + string.digits, k = N))
    if not string.startswith("0"):
      print("https://prnt.sc/" + str(r) + ' ' + f"{i}")
  x = int(input("How many links would you like to generate? please input a number."))
  for i in range(x):
    gen(x)
  q = input("Would you like to generate more? (say 'y' or 'n'.)")
  if q == "y":
    main()
  else:
   quit()
main()
>>>How many links would you like to input? Please put a number.3
>>>https://prnt.sc/(insert random string here, not here because there are scams on lightshot)
>>>https://prnt.sc/(random string)
>>>https://prnt.sc/(random string)

I've tried looking it up and asking a friend, and i am either wayyy too tired or just don't know what to do. prob both, as i am pretty new to python. Any help I could receive here?


Solution

  • The error comes from your string.startswith("0")

    The string module doesn't have that method.

    You need to call the startswith() method on a string object.

    From your code I will assume that you want to use startswith on the random string r

    Here is the fixed code that runs:

    import random
    import string
    
    
    def main():
        def gen(x):
            N = 6
            r = ''.join(random.choices(string.ascii_lowercase + string.digits, k=N))
            if not r.startswith("0"):
                print("https://prnt.sc/" + str(r) + ' ' + f"{i}")
    
        x = int(input("How many links would you like to generate? please input a number."))
        for i in range(x):
            gen(x)
        q = input("Would you like to generate more? (say 'y' or 'n'.)")
        if q == "y":
            main()
        else:
            quit()
    
    if __name__ == '__main__':
        main()