学习Python并尝试获取字符串的前两个字母和最后两个字母

时间:2010-03-21 00:20:35

标签: python

这是我的代码:

# 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

不幸的是我的程序没有运行。 :(我确定我忽略了一些东西,因为我是Python的新手。

这是错误:

> 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'

感谢帮助人员。 :d

3 个答案:

答案 0 :(得分:4)

错位的括号:

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

顺便说一下:

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

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

答案 1 :(得分:4)

您的直接问题是s[len(s-1)],而不是s[len(s)-1]

您也可以简化为s[:2] + s[-2:]

答案 2 :(得分:2)

最后一部分有错误:

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

你可以考虑用更加pythonic的方式重写它:

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