有没有办法在使用`end =`时避免使用新行

时间:2016-09-17 18:41:45

标签: python python-3.5

我刚刚开始使用python,我正在创建一个简单的程序,它将询问用户是谁的问题,然后从文本文件中我将提取一个特定的行并打印该行以及该行 - 在最后,我将添加他们的答案。这是代码。

    question = input("do you want to print the line")
    if "yes" in question:
        print(open("tp.txt").readlines()[:10][-1],end=question) 

问题是,end=question)会将用户的答案放在新行上。我知道end=\n相同。所以我只是想知道是否有一种方法或替代方法可以阻止'end ='自动创建新行?

 print(open("tp.txt").readlines()[:10][-1],

是我打开并从文件中读取特定行的方式 因为它是一个'好'的捷径,而不是做with open (filename.txt,'r') as f:

1 个答案:

答案 0 :(得分:0)

问题是readlines()返回的行包含结尾换行符:

$ echo 'a
> b
> c
> ' > test_file.txt
$ python3
Python 3.5.2 (default, Jul  5 2016, 12:43:10) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> with open('test_file.txt') as f:
...     print(f.readlines())
... 
['a\n', 'b\n', 'c\n', '\n']

请参阅\n?注意差异:

>>> print('a\n')
a

>>>

>>> print('a')
a
>>>

所以你要删除它:

>>> with open('test_file.txt') as f:
...     for line in f:
...         print(line.rstrip('\n'), end='<something>')
... 
a<something>b<something>c<something><something>>>> 
相关问题