How can I remove a trailing newline?

前端 未结 28 3526
感动是毒
感动是毒 2020-11-21 23:27

What is the Python equivalent of Perl\'s chomp function, which removes the last character of a string if it is a newline?

28条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-21 23:54

    If you are concerned about speed (say you have a looong list of strings) and you know the nature of the newline char, string slicing is actually faster than rstrip. A little test to illustrate this:

    import time
    
    loops = 50000000
    
    def method1(loops=loops):
        test_string = 'num\n'
        t0 = time.time()
        for num in xrange(loops):
            out_sting = test_string[:-1]
        t1 = time.time()
        print('Method 1: ' + str(t1 - t0))
    
    def method2(loops=loops):
        test_string = 'num\n'
        t0 = time.time()
        for num in xrange(loops):
            out_sting = test_string.rstrip()
        t1 = time.time()
        print('Method 2: ' + str(t1 - t0))
    
    method1()
    method2()
    

    Output:

    Method 1: 3.92700004578
    Method 2: 6.73000001907
    

提交回复
热议问题