Python 3.2 - 字符串连接和格式化行为不如预期
我想从几个变量中创建一个“完整文件名”的变量,但在拼接字符串和格式化字符串时,结果和我预期的不太一样。
我的代码如下:
file_date = str(input("Enter file date: "))
root_folder = "\\\\SERVER\\FOLDER\\"
file_prefix = "sample_file_"
file_extension = ".txt"
print("")
print("Full file name with concatenation: ")
print(root_folder + file_prefix + file_date + file_extension)
print("Full file name with concatenation, without file_extension: ")
print(root_folder + file_prefix + file_date)
print("")
print("")
print("Full file name with string formatting: ")
print("%s%s%s%s" % (root_folder, file_prefix, file_date, file_extension))
print("Full file name with string formatting, without file_extension: ")
print("%s%s%s" % (root_folder, file_prefix, file_date))
print("")
当我运行这个脚本时,输出是:
C:\Temp>python test.py
Enter file date: QT1
Full file name with concatenation:
.txtRVER\FOLDER\sample_file_QT1
Full file name with concatenation, without file_extension:
\\SERVER\FOLDER\sample_file_QT1
Full file name with string formatting:
.txtRVER\FOLDER\sample_file_QT1
Full file name with string formatting, without file_extension:
\\SERVER\FOLDER\sample_file_QT1
我本来希望它能把“.txt”加在最后,但结果却把字符串的前四个字符替换掉了。
我该怎么把扩展名变量加到字符串的末尾,而不是替换掉前面的字符呢?
除了想知道怎么解决这个具体的问题,我还想了解一下我为什么会遇到这个问题。我哪里做错了?或者说我对Python 3.2的行为有什么不了解的地方吗?
2 个回答
3
用这一行代码来去掉换行符:
file_date = str(input("Enter file date: ")).rstrip()
8
我觉得你例子中用的这个输入方法,像这样:
file_date = str(input("Enter file date: "))
可能在最后返回了一个换行符。
这会导致光标在你尝试打印的时候回到行的开头。你可能需要把input()的返回值去掉多余的空白。