【问题标题】:appending first 2 characters and last 2 characters from a single given string附加单个给定字符串的前 2 个字符和后 2 个字符
【发布时间】:2014-07-07 09:35:19
【问题描述】:

both_ends

给定一个字符串s,返回一个由前2和后2组成的字符串 原始字符串的字符,所以'banana' 给出'bana' 但是, 如果字符串长度小于 2,则返回空字符串。

我的代码:

def both_ends(string):
    for item in string:
        if len(item) < 2:
            return ["empty"]
        else:
            (item [0])(item [1]).append(item (len(item)-1))(item (len(item) -2))


string=["jelly"]
both_ended=both_ends(string)
print both_ended

错误信息:

  File "both_ends.py", line 18, in <module>
    both_ended=both_ends(string)
  File "both_ends.py", line 14, in both_ends
    (item [0])(item [1]).append(item (len(item)-1))(item (len(item) -2))
TypeError: 'str' object is not callable

【问题讨论】:

  • 你用什么来学习Python?您对() 的使用是......不是Python。
  • return ["empty"] 返回一个包含一个元素的列表(字符串“empty”)。我认为您应该只返回一个没有内容的字符串 (=> "")。

标签: python string append character


【解决方案1】:

您可以更简单地使用字符串切片来做到这一点:

def get_22(s):
    return s[:2]+s[-2:] if len(s) >=2 else ''

>>> print get_22("banana")
bana
>>> print get_22("tomato")
toto
>>> print get_22("abc")
abbc

【讨论】:

  • 是的,认真的。你为什么要否决这个?它的效果很好
猜你喜欢
  • 2020-04-01
  • 2014-02-15
  • 1970-01-01
  • 2011-03-29
  • 2022-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多