我有这个代码:
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()我正在尝试将字符串变量看起来像这样的格式: suffixes=c(".fileA",".fileB".....)但是添加最后的括号不起作用。 当我按原样运行此代码时,我得到:
suffixes=c(".file1",".FILE2",".file3",".fiLe4" New String )知道发生了什么或如何解决它?
I have this code:
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()I'm trying to get the string variable to look like this format: suffixes=c(".fileA",".fileB".....) but adding on the final parenthesis is not working. When I run this code as is, I get:
suffixes=c(".file1",".FILE2",".file3",".fiLe4" New String )Any idea what's going on or how to fix it?
最满意答案
这样做你想要的吗?
>>> filenames=["file1","FILE2","file3","fiLe4"] >>> c = "suffixes=c(%s)" % (",".join('".%s"' %f for f in filenames)) >>> c 'suffixes=c(".file1",".FILE2",".file3",".fiLe4")'使用string.join是一种更好的方法,可以将常用分隔符添加到项列表中。 它不需要在添加分隔符之前检查是否在最后一个项目上,或者在您尝试剥离添加的最后一个项目的情况下。
此外,您可能需要查看列表理解
Does this do what you want?
>>> filenames=["file1","FILE2","file3","fiLe4"] >>> c = "suffixes=c(%s)" % (",".join('".%s"' %f for f in filenames)) >>> c 'suffixes=c(".file1",".FILE2",".file3",".fiLe4")'Using a string.join is a much better way to add a common delimiter to a list of items. It negates the need to have to check for being on the last item before adding the delimiter, or in your case attempting to strip off the last one added.
Also, you may want to look into List Comprehensions
更多推荐
发布评论