python中的For循环不会将输出打印为字符串

2024-04-26 06:25:45 发布

您现在位置:Python中文网/ 问答频道 /正文

def catenateLoop(strs):
    outputString = ""
    for strings in strs:
        outputString = outputString + strings         
    print outputString

我使用上面的代码使用for循环将字符串列表连接到单个字符串中。没错,代码输出的是正确的连接,但由于某些原因,代码没有作为字符串输出。例如,catenateLoop(['one','two','three'])正在打印onetwothree而不是'onetwothree'。我试过几种不同的格式,但似乎不明白为什么它不能打印成字符串。有什么想法吗?在


Tags: 字符串代码in列表fordef原因one
3条回答

“print”只打印outputString的内容;如果要输出outputString的表示形式(包括引号),请尝试“print repr(outputString)”。在

您可以使用str.format并将输出包装成您想要的任何内容:

def catenateLoop(strs):
    outputString = ""
    for strings in strs:
        outputString = outputString + strings
    print "'{}'".format(outputString)

In [5]: catenateLoop(['one', 'two', 'three'])
'onetwothree'

也可以使用str.join连接列表内容:

^{pr2}$

__repr__救命!在

这会给你想要的结果

def catenateLoop(strs):
    outputString = ""
    for strings in strs:
        outputString = outputString + strings         
    print repr(outputString)

catenateLoop(['one', 'two', 'three'])

#output: 'onetwothree'

另请参见Why are some Python strings are printed with quotes and some are printed without quotes?

相关问题 更多 >