I want to create a "full file name" variable from several other variables, but the string concatenation and string format operations aren't behaving开发者_C百科 the way I expect.
My code is below:
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("")
The output when I run the script is:
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
I was expecting it to concatenate the ".txt" at the very end, except it's replacing the first four characters of the string with it instead.
How do I concatenate the extension variable to the end of the string instead of having it replace the first n characters of the string?
In addition to how to solve this particular problem, I'd like to know why I ran into it in the first place. What did I do wrong/what Python 3.2 behavior am I not aware of?
I think the method input used in your example, like so:
file_date = str(input("Enter file date: "))
may be returning a carriage return character at the end.
This causes the cursor to go back to the start of the line when you try to print it out.
You may want to trim the return value of input().
Use this line instead to get rid of the line feed:
file_date = str(input("Enter file date: ")).rstrip()
精彩评论