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

标签 python python-3.x string-formatting string-concatenation

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

我的代码如下:

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”,只是它用它替换了字符串的前四个字符。

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

除了如何解决这个特定问题之外,我还想知道为什么我会首先遇到它。我做错了什么/我不知道什么 Python 3.2 行为?

最佳答案

我认为您的示例中使用的方法 input 是这样的:

file_date = str(input("Enter file date: "))

最后可能会返回一个回车符。
当您尝试打印出来时,这会导致光标返回到该行的开头。 您可能想要修剪 input() 的返回值。

关于Python 3.2 - 连接和字符串格式化行为不符合预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6256369/

相关文章:

python - 在 kivyMD 中更改 MDToolbar 中图标的颜色?

python - 连分数 Python

python-3.x - 'range'对象不支持python3中的项目分配

c++ - 如何在非托管 C++ 代码中检查字符串是否具有有效的文件路径或目录路径格式?

php - 使用 %03.3f 填充不起作用

Python difflib,获取偏移量

python - 如何将元素附加到 numpy 数组

python - 如何在打印之前对 JSON float 据进行排序

python - Selenium Python - 如何让我的程序在特定元素出现时单击它?

printing - 打印表格的 Pythonic 方式