2010-08-19 55 views
0

我有這樣的代碼:字符串串聯在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 
) 

任何想法發生了什麼或如何解決它?

回答

11

這是做你想做的嗎?

>>> 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是向項目列表中添加公共分隔符的更好方法。它不需要在添加分隔符之前檢查最後一個項目,或者在你的情況下試圖剝離添加的最後一個項目。

此外,您可能想看看List Comprehensions

+0

對於'.join()'而不是'+ ='而言+1。投擲一個'.lower()',它看起來像他想要的。 – 2010-08-19 20:00:14

+0

我認爲低層不是必需的,因爲他的例子沒有說明它的必要性。他的代碼不會嘗試小寫輸入,他所需的格式包括''.fileA''和''fileB'',但是他的輸入有'file1'和''file2'' – sberry 2010-08-19 20:02:05

+0

是的!這是完美的,更簡潔!謝謝! – Brian 2010-08-19 20:06:02

1

這是怎麼回事是因爲到底是開始之前,這個切片返回一個空字符串

。嘗試在命令行中執行以下操作:

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

解決方案是不是做

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

但我認爲你真正想要的是剛落最後三個字符。

filestring=filestring[:-3] 

更好的解決方案是使用字符串的連接方法爲sberry2A suggested

2

看起來你可能會嘗試使用Python編寫的R腳本,它可以是一個快速的解決方案,如果你不」但是在這種情況下,R-only解決方案實際上相當簡單:

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