You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python指定长度字符串缩写函数实现求助(固定代码框架)

实现字符串缩写函数需求及解决方法

不可修改的代码框架

##
# Returns the abbreviated version of a string.
# @param string the string from which the abbreviation is constructed
# @param size the maximum number of characters in the abbreviation
# @returns the abbreviated version of the string, which is formed from 
#       size number of characters at the front of of the string
#

def abbreviation(string, size) :


testStr = input()
testSize = int(input())
print(abbreviation(testStr, testSize))

这是计算机科学课程作业,需在上述框架基础上完成abbreviation函数,要求根据输入的size值返回字符串前size个字符作为缩写。

之前尝试的错误写法分析

写法1的问题

def abbreviation(string, size) :
    _len = len(string);

    # Print 1st character
    print(string[range(0, testSize)], end="");

testStr = input()
testSize = int(input())
print(abbreviation(testStr, testSize))
  • Python字符串切片不支持直接用range对象作为索引,切片语法应为[起始索引:结束索引]
  • 函数内错误调用了全局变量testSize,应使用参数传入的size
  • 题目要求函数返回缩写字符串,而非直接打印,外层print会输出函数的返回值(无return时会输出None)

写法2的问题

def abbreviation(string, size) :
    _len = len(string);

    # Print 1st character
    print(string[0], end="");


testStr = input()
testSize = int(input())
print(abbreviation(testStr, testSize))
  • 仅固定截取第一个字符,未根据size参数动态调整长度
  • 同样错误地直接打印内容,未返回结果,外层print会输出None

正确实现方法

利用Python的切片语法即可快速实现需求,同时切片会自动处理size大于字符串长度的边界情况(直接返回原字符串)。修改后的完整代码如下:

##
# Returns the abbreviated version of a string.
# @param string the string from which the abbreviation is constructed
# @param size the maximum number of characters in the abbreviation
# @returns the abbreviated version of the string, which is formed from 
#       size number of characters at the front of of the string
#

def abbreviation(string, size) :
    # 截取前size个字符,size超出字符串长度时返回原字符串
    return string[:size]


testStr = input()
testSize = int(input())
print(abbreviation(testStr, testSize))

关键说明

  • string[:size]等价于string[0:size],表示从索引0开始截取到索引size的前一个位置,正好获取前size个字符
  • 函数通过return返回结果,外层print会输出该结果,完全符合给定的代码框架逻辑

内容的提问来源于stack exchange,提问作者FoxKingLD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 15:46:05