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

Python不使用f-string或str()如何实现int与str混合打印

问题说明

需要实现读取文本文件、输出最长行内容及其对应词数的功能,初始编写的实现代码如下:

with open("txt.txt") as file:
    for line in file:
        words = line.split()
        words_count += len(words)
        if maxlines == 0 or len(words) > len(maxlines.split()):
            maxlines = line
        sentences.append(line)

print("Longest line has " + maxlines_len + " words: " + maxlines)

上述代码直接用+拼接字符串和整数类型变量时会抛出TypeError,要求在既不使用f-string、也不手动调用str()做类型转换的前提下,找到可正常运行的替代打印方案。

可行实现方案

首先要注意原代码存在变量未初始化的问题,运行前需要在循环前补全初始化语句:maxlines = ""、sentences = []、words_count = 0。另外代码中单独维护的maxlines_len变量没有必要,直接通过len(maxlines.split())即可实时获取最长行的词数,能避免变量值和实际行内容不匹配的bug。

满足限制要求的打印实现共有三种:

  • 利用print函数的多参数传参特性
    print支持接收任意多个不同类型的位置参数,会自动完成类型转换后按默认分隔符(空格)拼接输出,不需要手动做类型处理,写法最简洁:
    maxlines_word_count = len(maxlines.split())
    print("Longest line has", maxlines_word_count, "words:", maxlines)
    
  • 使用%旧式字符串格式化语法
    通过%d占位符匹配整数、%s占位符匹配字符串,格式化逻辑会自动完成对应类型到字符串的转换,不属于f-string范畴,也不需要手动调用str():
    maxlines_word_count = len(maxlines.split())
    print("Longest line has %d words: %s" % (maxlines_word_count, maxlines))
    
  • 使用字符串format()方法
    通过花括号标记占位符,format()方法会自动处理传入参数的类型转换,完全符合限制要求:
    maxlines_word_count = len(maxlines.split())
    print("Longest line has {} words: {}".format(maxlines_word_count, maxlines))
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 04:18:30