Python 3.2 - 连接和字符串格式化行为不符合预期

tgx*_*iii 6 python string-concatenation string-formatting python-3.x

我想从其他几个变量创建一个"完整文件名"变量,但字符串连接和字符串格式操作的行为不符合我的预期.

我的代码如下:

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("")
Run Code Online (Sandbox Code Playgroud)

运行脚本时的输出是:

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
Run Code Online (Sandbox Code Playgroud)

我期待它在最后连接".txt",除了它用它替换字符串的前四个字符.

如何将扩展变量连接到字符串的末尾,而不是将其替换为字符串的前n个字符?

除了如何解决这个特殊问题,我想知道为什么我首先遇到它.我做错了什么/我不了解Python 3.2的行为?

hop*_*pia 8

我认为你的例子中使用的方法输入,如下所示:

file_date = str(input("Enter file date: "))
Run Code Online (Sandbox Code Playgroud)

可能会在结尾处返回回车符.
当您尝试将其打印出来时,这会导致光标返回到行的开头.您可能希望修剪input()的返回值.

  • 在Python 3中,输入返回一个字符串,因此不需要使用str. (3认同)