0

Im trying to iterate through a string and return the string length that has been declared in the function.

It will receive two parameters, x and chars. The function will return a string that is comprised of the values in chars from index 0 up to the index x-1.

The return I want to receive is

print rangeLoopStringParam1("bobsyouruncle", 5)
# -> "bobsy"
print rangeLoopStringParam1("supercalifragilisticexpialidoshus", 8)
# -> "supercal"

This is the code I have so far but I feel like Im not getting very far. Can anyone guide me through this problem?

def rangeLoopStringParam1(chars, x):
    for i in range(0, x, len(chars)):
        chars += chars
    return chars
Lynds.
  • 127
  • 12

4 Answers4

3

Whats wrong with list slicing?

def stringRange(chars, x):
    return chars[:x]

Whats going on here is we are treating the string as a list of characters, and we are telling python to give us the first x elements of the list (first x characters of string). Keep in mind, list slicing follows the syntax list[start:end] (in our case, start is implied to be 0). This means that, since lists start at 0, list slicing really returns a list of all elements with index from 0 (inclusive) to x (non inclusive).

For a better, more detailed explanation, see this great answer by Greg Hewgill on how list slices work.

Community
  • 1
  • 1
stelioslogothetis
  • 9,371
  • 3
  • 28
  • 53
2

On an extra note, you can do lambda function.

yourFunction = lambda string, num: string[:num]

print(yourFunction("bobsyouruncle", 5))

returns

bobsy

for reference:

Python3 Docs

Python course Doc

Prajwal
  • 3,930
  • 5
  • 24
  • 50
1

Python has some pretty powerful built in functionality. One of them (slicing) does exactly what you're asking for.

def rangeLoopStringParam1(chars, x):
    return chars[:x]
Matt Messersmith
  • 12,939
  • 6
  • 51
  • 52
0

You can directly split you string using :

new_string = string[:n] with n being the length you want.

Nicolas M.
  • 1,472
  • 1
  • 13
  • 26