1

我正在尝试使用 linecache 连接来自两个不同行的 2 个字符串,但是当我尝试时,输出总是在 2 行而不是 1 行。

文件中的文字:

你好

世界

代码:

import linecache
import easygui

a=linecache.getline("textfile.txt",1)
b=linecache.getline("textfile.txt",2)

easygui.msgbox (a+b)

结果:

结果(消息)是:两行hello world (第一行是hello,第二行是world)

这不是我想要的,我想要这个:hello world on a single line

任何帮助,将不胜感激!:-)

PS对不起我的英语!

4

2 回答 2

1

从第一个字符串中删除换行符:

easygui.msgbox a.rstrip("\n\r") + b
于 2017-02-13T19:28:49.137 回答
1

你想去掉尾随的换行符:

a = linecache.getline("textfile.txt",1).rstrip("\n")
b = linecache.getline("textfile.txt",2).rstrip("\n")

str.rstrip("\n")从字符串的右侧去除换行符。

于 2017-02-13T19:29:07.360 回答