[英]Unable to concatenate strings in Python2.7
I'm trying to concatenate two strings in my function. 我正在尝试在函数中连接两个字符串。 I tried all concatenation, but those two strings just don't concatenate one after another, instead, shorter strings B(length = s) substitute the first s units of longer string A.
我尝试了所有串联,但那两个字符串只是不一个接一个地串联,而是用较短的字符串B(length = s)代替较长的字符串A的前s个单位。
I read some data from input file, and store third line whose content is "00001M035NNYY1111111" into a variable called applicant: 我从输入文件中读取了一些数据,并将内容为“ 00001M035NNYY1111111”的第三行存储到一个名为“申请人”的变量中:
data = open("input.txt").read().split('\n')
applicant = str(data[2])
I want to add an integer 8 at the end of applicant
, so the new applicant
will be "00001M035NNYY11111118". 我想在
applicant
的末尾添加一个整数8,因此新applicant
将为“ 00001M035NNYY11111118”。 I tried applicant += str(8)
and "".join((applicant, str(8)))
and other concatenation methods, but all of them only give me "80001M035NNYY1111111"... Does anyone know why this happened and how am I suppose to do to get my intended result. 我尝试了
applicant += str(8)
和"".join((applicant, str(8)))
和其他串联方法,但是它们都只给我“ 80001M035NNYY1111111” ...有人知道为什么会这样以及如何我是否应该做以获得预期的结果。
You probably have Windows line endings in your file: \\r\\n
. 您的文件中可能有Windows行尾:
\\r\\n
。 By splitting on \\n
, you leave the \\r
, which returns to the beginning of the line. 通过在
\\n
上分割,您将留下\\r
,它返回到行的开头。 You can trim it manually: 您可以手动修剪它:
with open("input.txt") as f:
data = [line.rstrip() for line in f]
This should work 这应该工作
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> data = open("input.txt").read().split("\n")
>>> applicant = data[2] + str(8)
>>> print applicant
00001M035NNYY11111118
>>>
There is probably something wrong with your text file if this does not work. 如果这不起作用,则您的文本文件可能存在问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.