简体   繁体   中英

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.

I read some data from input file, and store third line whose content is "00001M035NNYY1111111" into a variable called applicant:

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". 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.

You probably have Windows line endings in your file: \\r\\n . By splitting on \\n , you leave the \\r , which returns to the beginning of the line. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM