jeudi 7 janvier 2016

Python .join[] multiplys total string characters across multiple lines

I am working on a personal project to help my understanding of python 3.4.2 looping and concatenating strings from multiple sources.

My goal with this is to take 'string' use join and call len() inside to build a string it is multiplying my results. I would like the lengths to be 5 then 10 then 15. Right now it is coming out 5 then 25 then 105. If I keep going I get 425,1705,6825,etc...

I hope I'm missing something simple, but any help would be amazing. I'm also trying to do my joins efficiently (I know the prints aren't, those are for debugging purposes.)

I used a visualized python tool online to step through it and see if I could figure it out. I just am missing something. http://ift.tt/1lIvgfK

Thank you in advance!

import random

def main():
    #String values will be pulled from
    string = 'valuehereisheldbythebeholderwhomrolledadtwentyandcriticalmissed'

    #Initial string creation
    strTest = ''
    print('strTest Blank: ' + strTest)

    #first round string generation
    strTest = strTest.join([string[randomIndex(string.__len__())] for i in range(randomLength())])
    print('strTest 1: ' + strTest)
    print('strTest 1 length: ' + str(strTest.__len__()))

    #second round string generation
    strTest = strTest.join([string[randomIndex(string.__len__())] for i in range(randomLength())])
    print('strTest 2: ' + strTest)
    print('strTest 2 length: ' + str(strTest.__len__()))

    #final round string generation
    strTest = strTest.join([string[randomIndex(string.__len__())] for i in range(randomLength())])
    print('strTest 3: ' + strTest)
    print('strTest 3 length: ' + str(strTest.__len__()))

def randomIndex(index):
    #create random value between position 0 and total string length to generate string
    return random.randint(0,index)
def randomLength():
    #return random length for string creation, static for testing
    return 5
    #return random.randint(10,100)

main()
# output desired is 
# strTest 1 length: 5
# strTest 2 length: 10
# strTest 3 length: 15




Aucun commentaire:

Enregistrer un commentaire