从给定字符串中提取前两个和后两个字符并添加

-3 投票
1 回答
2281 浏览
提问于 2025-04-18 06:59

both_ends

给定一个字符串 s,要返回一个新字符串,这个新字符串由原字符串的前两个字符和最后两个字符组成。比如说,字符串 '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

1 个回答

0

你可以用字符串切片的方法来更简单地实现这个功能:

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

撰写回答