Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Beginner Exercise Help
#1
First post ever so mods please be nice. Let me know if I need to repost.

Anyways, just getting started with Python, first language other than VBA. I know the solution to this particular exercise. Just curious as to why my particular solution doesn't work. Thank you! Link below.

https://codingbat.com/prob/p153599




Given a string, return a new string where the first and last chars have been exchanged.

front_back('code') → 'eodc'
front_back('a') → 'a'
front_back('ab') → 'ba'


def front_back(str):
  first = str[0]
  last = str[-1]
  middle = str[1:-2]
  return last + middle + first
receiving this error(what does this error mean?): string index out of range
Reply
#2
Hi, what input did you give to the function to get the error?
When you get an error to show, please could you show the full error in error code tags.

string index out of range means you are trying to access part of a string by an index that is outside of the range of that the string contains.

The following example code has the following index numbers shown below the characters
code
0123
Reply
#3
Yes you code not retuns the correct results but it works i dont get string index out of range...
At the line 1 you access to the first char of string
At the line 2 you access to last char of string
At the line 3 you access the chars at index 1 and extending up to but not including index of 2 last chars

There are 2 faults, first you need to check give str len if the len <= 1 you should return as result the str becuase if you continue like your code when you pass a as str you will get as results "aa" and not "a" as the code practice want, thats occurs because at line 1 and at line 2 you get from each line a as result,
second you line 3 should be middle = str[1:-1] chars at index 1 and extending up to but not including index of last char

The correct code should be

def front_back(str):
    if len(str) <=1:
        return str
    first = str[0]
    last = str[-1]
    middle = str[1:-1]
    return last + middle + first
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020