Python 从单个给定字符串中追加前2个字符和后2个字符
Python 从单个给定字符串中追加前2个字符和后2个字符,python,string,append,character,Python,String,Append,Character,两端 给定一个字符串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 (le
两端
给定一个字符串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
def两端(字符串):
对于字符串中的项目:
如果长度(项目)<2:
返回[“空”]
其他:
(项目[0])(项目[1])。追加(项目(项目-1))(项目(项目-2))
字符串=[“果冻”]
两端=两端(字符串)
打印两个字符
错误消息:
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
文件“both_ends.py”,第18行,在
两端=两端(字符串)
文件“both_ends.py”,第14行,在两端
(项目[0])(项目[1])。追加(项目(项目-1))(项目(项目-2))
TypeError:“str”对象不可调用
您可以更简单地使用字符串切片:
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
你用什么来学习Python?您对
()
的使用是。。。不是Python。return[“empty”]
返回一个包含一个元素的列表(字符串“empty”)。我想你应该只返回一个没有内容的字符串(=>“
)。是的,说真的。你为什么要投反对票?它工作得很好