字符串连接在Python中产生不正确的输出?(String concatenation produces incorrect output in Python?)

编程入门 行业动态 更新时间:2024-10-24 10:14:52
字符串连接在Python中产生不正确的输出?(String concatenation produces incorrect output in Python?)

我有这个代码:

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

更多推荐

本文发布于:2023-08-07 09:53:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1463802.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   不正确   Python   String   output

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!