2017-02-11 9 views
0

我試圖添加一些輸入到一起來形成一個文件名,但它們之間似乎有空格,我有試圖擺脫使用替換的空間,並加入。但它說聯接沒有被定義,'元組'對象沒有屬性'replace'。請幫助 我的代碼是:試圖從字符串中刪除空格,但得到一個錯誤說'元組'對象沒有屬性'替換'

from turtle import Turtle, Screen 

    def k100(): 
      tsave = Turtle() 
      tsavescreen = tsave.getscreen() 
      pictype = input("What type of photo would you like this to be saved as? (png, jpg, pdf, ...) ") 
      name = input("What would you like to call your masterpiece? ") 
      fnws = name,".",pictype #fnws means file_name_with_spaces 
      join(fnws) 
      fnns = fnws.replace(" ", "") #fnns means file_name_no_spaces 
      tsavescreen.getcanvas().postscript(file=fnns, colormode='color') 
      #open("C:\Users\GURNHH\OneDrive - Rugby School\ICT\Python").close() 
      #open("pythontest11.pdf").close() 
      print("It has been saved as: ", fnns) 
      print("It has been saved as: ", fnns) 

回答

1

作爲使用,創建一個元組,和你需要的是一個字符串,你應該做到以下幾點:

變化:

fnws = name,".",pictype 

要:

fnws = name, + "." + pictype 

現在,fnws是一個String變量,所以你可以應用替換它。

此外,考慮到使用剝離法,與帶材可以去除要,簡單地寫任何字符(默認值被去除whitespcace):

fnws = (name, + "." + pictype).strip() 

string.strip(S [,字符])

返回刪除前導字符和尾隨字符的字符串副本 。如果省略字符或無,刪除空白字符 。如果給出而不是無,字符必須是字符串;該字符串中的字符 將從字符串的兩端剝離,此方法在 上調用。

0

如果你的變量有引導和/或尾隨空白,你可以調用strip函數。您可以使用它像這樣

fnws = "{}.{}".format(name.strip(),pictype.strip())

有關條功能的更多信息,你可以去這裏strip doc

+0

三江源這麼多! – Gurneyguy

+0

你知道我爲什麼不能打開文件嗎?我曾嘗試使用Adobe,Microsoft Edge和Word,但都沒有成功。 (順便說一句,我想保存一張烏龜畫的圖片) – Gurneyguy