Brian
Brian

Reputation: 4243

String concatenation produces incorrect output in Python?

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?

Upvotes: 0

Views: 358

Answers (3)

Michael Dunn
Michael Dunn

Reputation: 8313

It looks like you might be trying to use python to write an R script, which can be a quick solution if you don't know how to do it in R. But in this case the R-only solution is actually rather simple:

R> filenames= c("file1","FILE2","file3","fiLe4")
R> suffixes <- paste(".", tolower(filenames), sep="")
R> suffixes
[1] ".file1" ".file2" ".file3" ".file4"
R> 

Upvotes: 2

AFoglia
AFoglia

Reputation: 8128

What's going on is that this slicing returns an empty string

filestring=filestring[-1:-4]

Because the end is before the begin. Try the following on the command line:

>>> a = "hello world"
>>> a[-1:-4]
''

The solution is to instead do

filestring=filestring[:-4]+filestring[-1:]

But I think what you actually wanted was to just drop the last three characters.

filestring=filestring[:-3]

The better solution is to use the join method of strings as sberry2A suggested

Upvotes: 1

sberry
sberry

Reputation: 132018

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

Upvotes: 11

Related Questions