Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append two strings in Python?

Tags:

python

string

I have done this operation millions of times, just using the + operator! I have no idea why it is not working this time, it is overwriting the first part of the string with the new one! I have a list of strings and just want to concatenate them in one single string! If I run the program from Eclipse it works, from the command-line it doesn't! The list is:

["UNH+1+XYZ:08:2:1A+%CONVID%'&\r", "ORG+1A+77499505:ABC+++A+FR:EUR++123+1A'&\r", "DUM'&\r"]

I want to discard the first and the last elements, the code is:

        ediMsg = ""
        count = 1
        print "extract_the_info, lineList ",lineList
        print "extract_the_info, len(lineList) ",len(lineList)
        while (count < (len(lineList)-1)):
            temp = ""
#            ediMsg = ediMsg+str(lineList[count])
#            print "Count "+str(count)+" ediMsg ",ediMsg 
            print "line value : ",lineList[count]
            temp = lineList[count]
            ediMsg += " "+temp
            print "ediMsg     : ",ediMsg
            count += 1
            print "count ",count

Look at the output:

extract_the_info, lineList  ["UNH+1+XYZ:08:2:1A+%CONVID%'&\r", "ORG+1A+77499505:ABC+++A+FR:EUR++123+1A'&\r", "DUM'&\r"]
extract_the_info, len(lineList)  8
line value :  ORG+1A+77499505:ABC+++A+FR:EUR++123+1A'&
ediMsg     :  ORG+1A+77499505:ABC+++A+FR:EUR++123+1A'&
count  2

line value :  DUM'&
 DUM'&     :  ORG+1A+77499505:ABC+++A+FR:EUR++123+1A'&
count  3

Why is it doing so!?

like image 475
wheisenberg Avatar asked May 20 '26 14:05

wheisenberg


1 Answers

While the two answers are correct (use " ".join()), your problem (besides very ugly python code) is this:

Your strings end in "\r", which is a carriage return. Everything is fine, but when you print to the console, "\r" will make printing continue from the start of the same line, hence overwrite what was written on that line so far.

like image 70
balpha Avatar answered May 23 '26 05:05

balpha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!