views:

62

answers:

3

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?

+9  A: 

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

sberry2A
+1 for `.join()` instead of `+=`. Toss in a `.lower()` and it would look like he wants.
Nick T
I figured the lower wasn't necessary since his example doesn't illustrate the need for it. His code doesn't attempt to lowercase the input and his desired format included `'.fileA'` and `'fileB'` but his input has `'file1'` and `'file2'`
sberry2A
Yes! This is perfect and much more concise! Thank you!
Brian
A: 

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

AFoglia
A: 

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> 
Michael Dunn