the objective is as follows:
Write a function splitWord(word, numOfChar) that takes in a word and a number as arguments. The function will split the word into smaller segments with each segment containing the number of letter specified in the numOfChar argument. These segments are stored and returned in a list.

Examples

>>> splitWord('google', 2)
    ['go', 'og', 'le']
    >>> splitWord('google', 3)
    ['goo', 'gle']
    >>> splitWord('apple', 1)
    ['a', 'p', 'p', 'l', 'e']
    >>> splitWord('apple', 4)
    ['appl', 'e']

I spent ages messing around try to find ways, eventually i got it working and started testing it, however, for some reason it doesn't accept duplicate values?!

def splitWord(word, numOfChar):
	r = []
	h = len(word)/numOfChar
	while True:
		if len(word) == 0:
			break
		else:
			r.append(word[0:numOfChar:1])
			word = word.replace(word[0:numOfChar:1], '')
	return r

Help would be appreciated, after spending so much time up all night trying to learn and getting stuck on this...
Anyway, thanks for any help.

def splitWord(word, length):
    r = []
    for count in range(0, len(word), length):
        r.append(word[count:count+length])
    return r

Your capitalization is idiosyncratic (probably due the site not following the PEP8

def splitWord(word, numOfChar):
    r = []
    for count in range(0, len(word), numOfChar):
        r.append(word[count:count+numOfChar])
    return r

Your capitalization is idiosyncratic (probably due the site not following the PEP8

Thanks for the help! i wish i could have thought that up. Im too now anyway, i have been trying to learn for the past 16 hours or so.
Could you explain exactly how your code works?

Advance counter in length steps and take length long pieces from that index forward, stop when counter is equal or greater than length of word to split. The appending to result bit you did yourself already.

You use "replace" so it replaces all text that is equal (duplicates), when you should slice off the word.

def split_word(word, numOfChar):
	r = []
#	h = len(word)/numOfChar     ## not used
	while True:
		if len(word) == 0:
			return r
		else:
			r.append(word[0:numOfChar])
			word = word[numOfChar:]         ## changed
	return r

print split_word("Asentencewithduplicateduplicatewords", 5)

Thanks for the help everyone, much appreciated.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.