如何在Python中连接两个字符串?

2 投票
6 回答
27868 浏览
提问于 2025-04-15 12:34

我已经做过这个操作无数次了,都是用 + 这个符号!我不知道这次为什么不行,它把字符串的前面部分给新内容覆盖掉了!我有一个字符串列表,只想把它们合并成一个字符串!在Eclipse里运行程序是可以的,但在命令行里就不行!

这个列表是:

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

我想丢掉第一个和最后一个元素,代码是:

        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

看看输出结果:

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

为什么会这样呢!?

6 个回答

11

问题不在于字符串的连接(虽然那部分可以稍微整理一下),而是在于你打印的方式。你字符串中的 \r 是个特殊字符,它会覆盖之前打印的内容。

可以使用 repr(),像这样:

...
print "line value : ", repr(lineList[count])
temp = lineList[count]
ediMsg += " "+temp
print "ediMsg     : ", repr(ediMsg)
...

来打印你的结果,这样可以确保任何特殊字符不会影响输出。

32

虽然这两个答案都是对的(用 " ".join()),但你的问题(除了代码看起来很丑)是这样的:

你的字符串结尾有一个"\r",这是一个回车符。这样没问题,但当你在控制台打印的时候,"\r"会让打印从同一行的开头继续,这样就会覆盖掉这一行之前写的内容。

21

你应该使用下面这个,别再纠结于这个噩梦了:

''.join(list_of_strings)

撰写回答