How can I remove a trailing newline?

前端 未结 28 3925
感动是毒
感动是毒 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:53

    s = '''Hello  World \t\n\r\tHi There'''
    # import the module string   
    import string
    # use the method translate to convert 
    s.translate({ord(c): None for c in string.whitespace}
    >>'HelloWorldHiThere'
    

    With regex

    s = '''  Hello  World 
    \t\n\r\tHi '''
    print(re.sub(r"\s+", "", s), sep='')  # \s matches all white spaces
    >HelloWorldHi
    

    Replace \n,\t,\r

    s.replace('\n', '').replace('\t','').replace('\r','')
    >'  Hello  World Hi '
    

    With regex

    s = '''Hello  World \t\n\r\tHi There'''
    regex = re.compile(r'[\n\r\t]')
    regex.sub("", s)
    >'Hello  World Hi There'
    

    with Join

    s = '''Hello  World \t\n\r\tHi There'''
    ' '.join(s.split())
    >'Hello  World Hi There'
    

提交回复
热议问题