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

Python不使用center方法实现字符串列表居中对齐的解决方案

实现方案

原代码问题

  • 函数定义接收参数x,但内部遍历使用了全局变量a,未使用传入的列表参数
  • 填充逻辑错误:给字符串左右两侧都添加了同等长度的空格,导致最终字符串长度超出最长字符串长度,不符合居中对齐要求
  • 函数直接打印内容,未按需求返回新的字符串列表
  • 测试函数定义在center_me内部,无法正常调用执行

正确实现

def center_me(str_list):
    # 计算列表中最长字符串的长度
    max_len = max(len(s) for s in str_list)
    result = []
    for s in str_list:
        # 计算总需填充的空格数
        total_pad = max_len - len(s)
        # 左侧填充空格取总空格数的一半向下取整,右侧填充剩余空格
        left_pad = total_pad // 2
        right_pad = total_pad - left_pad
        result.append(' ' * left_pad + s + ' ' * right_pad)
    return result

# 测试代码
if __name__ == '__main__':
    a = ["I LIKE","Dogs","Black Dogs, Green Dogs","Bad Dogs, Mean Dogs","All kinds of Dogs","I like Dogs", "Dogs"]
    centered_list = center_me(a)
    for line in centered_list:
        print(line)

运行输出效果

I LIKE       
        Dogs        
Black Dogs, Green Dogs
Bad Dogs, Mean Dogs 
 All kinds of Dogs  
    I like Dogs     
        Dogs        

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 05:27:02