真的很簡單的問題,但我正在努力解決這個問題......如果我有一個名為“first_second_third_fourth.txt”的檔案名,并且我想在創建新檔案時保留該字串的前幾個元素,我通常會運行如下內容:
import sys
file = sys.argv[1]
new_name = file.split("_")[0] "_newfile.txt"
輸出只是 first_newfile.txt
但是如果我想以某種方式獲得一個名為的新檔案,first_second_newfile.txt我無法想出一個簡單的解決方案來將它寫在一行中。
我試過:
import sys
file = sys.argv[1]
new_name = file.split("_")[0:1] "_newfile.txt"
但這會引發錯誤,因為您無法將字串連接到串列。我管理的唯一方法是將其拆分,但這似乎很混亂:
import sys
file = sys.argv[1]
new_name = file.split("_")[0] file.split("_")[1] "_newfile.txt"
我只是好奇是否有更短的方法來獲取拆分串列中的兩個元素而無需進行第二次迭代file.split("_")[1]?
uj5u.com熱心網友回復:
您可以使用.join()創建所需的檔案名:
f = "first_second_third_fourth.txt"
'_'.join(f.split('_')[0:2]) '.txt
輸出:
'first_second.txt'
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/375600.html
標籤:Python
下一篇:從串列中設定列名-Python
