delete
delete

Reputation:

Learning Python and trying to get first two letters and last two letters of a string

Here's my code:

# B. both_ends
# Given a string s, return a string made of the first 2
# and the last 2 chars of the original string,
# so 'spring' yields 'spng'. However, if the string length
# is less than 2, return instead the empty string.
def both_ends(s):
  if len(s) <= 2:
    return ""
  else:
    return s[0] + s[1] + s[len(s)-2] + s[len(s-1)]
  # +++your code here+++
  return

Unfortunately my program doesn't run. :( I'm sure I'm overlooking something since I'm a newbie with Python.

Here's the error:

> Traceback (most recent call last):
  File "C:\Users\Sergio\Desktop\google-python-exercises\google-python-exercises\basic\string1.py", line 120, in <module>
    main()
  File "C:\Users\Sergio\Desktop\google-python-exercises\google-python-exercises\basic\string1.py", line 97, in main
    test(both_ends('spring'), 'spng')
  File "C:\Users\Sergio\Desktop\google-python-exercises\google-python-exercises\basic\string1.py", line 44, in both_ends
    return s[0] + s[1] + s[len(s)-2] + s[len(s-1)]
TypeError: unsupported operand type(s) for -: 'str' and 'int'

Thanks for the help guys. :D

Upvotes: 1

Views: 5980

Answers (3)

Li0liQ
Li0liQ

Reputation: 11264

There is an error in the last part:

return s[0] + s[1] + s[len(s)-2] + s[len(s)-1]

You can think about rewriting it in a more pythonic way:

return s[0] + s[1] + s[-2] + s[-1]

Upvotes: 2

CB Bailey
CB Bailey

Reputation: 791481

Your immediate problem is s[len(s-1)] instead of s[len(s)-1] .

You can probably simplify to s[:2] + s[-2:] as well.

Upvotes: 4

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798526

Misplaced parenthesis:

return s[0] + s[1] + s[len(s)-2] + s[len(s)-1]

By the way:

return s[0] + s[1] + s[-2] + s[-1]

or

return s[:2] + s[-2:]

Upvotes: 4

Related Questions