字符串连接在Python中产生错误的输出?

Bri*_*ian 0 python string r concatenation

我有这个代码:

filenames=["file1","FILE2","file3","fiLe4"]


def alignfilenames():
    #build a string that can be used to add labels to the R variables.
    #format goal: suffixes=c(".fileA",".fileB")
    filestring='suffixes=c(".'
    for filename in filenames:
        filestring=filestring+str(filename)+'",".'

    print filestring[:-3]
    #now delete the extra characters
    filestring=filestring[-1:-4]
    filestring=filestring+')'
    print "New String"
    print str(filestring)

alignfilenames()
Run Code Online (Sandbox Code Playgroud)

我试图让字符串变量看起来像这种格式:suffixes=c(".fileA",".fileB".....)但添加最后的括号是行不通的.当我按原样运行此代码时,我得到:

suffixes=c(".file1",".FILE2",".file3",".fiLe4"
New String
)
Run Code Online (Sandbox Code Playgroud)

知道发生了什么或如何解决它?

sbe*_*rry 11

这样做你想要的吗?

>>> filenames=["file1","FILE2","file3","fiLe4"]
>>> c = "suffixes=c(%s)" % (",".join('".%s"' %f for f in filenames))
>>> c
'suffixes=c(".file1",".FILE2",".file3",".fiLe4")'
Run Code Online (Sandbox Code Playgroud)

使用string.join是一种更好的方法,可以将常用分隔符添加到项列表中.它不需要在添加分隔符之前检查是否在最后一个项目上,或者在您尝试剥离添加的最后一个项目的情况下.

此外,您可能需要查看列表理解