#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2013
    Posts
    1
    Rep Power
    0

    Red face Need help with splitting strings


    Hello, so I have a project in which I have to split a number which I enter into as many 'groups' as is determined by me as well. For instance,
    please enter a whole number: 123456
    input split: 2
    12
    34
    56

    However, I am having an issue. As it sits now, when I enter my number, it looks like this:
    1123456
    2
    3
    4
    5
    6

    Here is the code I am working with.
    wholenumber = (input('Please enter a whole number:'))
    split = int(input('Input the split:'))
    count = 0
    split_str = ''
    while wholenumber.isdigit() == True:
    ###for ch in wholenumber:
    ####split_str = ch + split_str
    ####count += 1
    ####if count <= split:
    ######print(split_str)
    ######wholenumber = ''
    ######count = 0

    Any help would be greatly appreciated
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    May 2009
    Posts
    530
    Rep Power
    34
    This never changes
    Code:
    while wholenumber.isdigit() == True:
    so should be an if statement not a while. You can use a for loop with step at 2, or count the number of letters printed
    Code:
    num=1234567
    num_as_str = str(num)
    if num_as_str.isdigit():
        endit = len(num_as_str)
        for ctr in range(0, endit, 2):
            next = ""
            if ctr < endit-1:
                next = num_as_str[ctr+1]
            print "%d = %s%s" % (ctr, num_as_str[ctr], next)
    
        print_after=2
        this_print = []
        for ltr in num_as_str:
            this_print.append(ltr)
            if print_after == len(this_print):
                print "".join(this_print)
                this_print = []
        if len(this_print):
            print "".join(this_print)
    Last edited by dwblas; September 24th, 2013 at 12:06 AM.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Location
    /dev/null
    Posts
    164
    Rep Power
    19
    If you're OK to parse it as a string, then you may try this:

    Code:
    i = 0 ## Initial index
    s = 3 ## Step
    x = '12345678' ## Number to be split
    l = len(x)
    
    for j in range(0, l, s):
        print (x[j:j+s])

IMN logo majestic logo threadwatch logo seochat tools logo