0

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?

3 Answers 3

11

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

Sign up to request clarification or add additional context in comments.

3 Comments

+1 for .join() instead of +=. Toss in a .lower() and it would look like he wants.
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'
Yes! This is perfect and much more concise! Thank you!
2

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> 

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.