Python:line=f.readlines () How to eliminate the ' \ n ' in line

Source: Internet
Author: User

#!/ust/bin/env Python3

f = open ("Name.txt")
Date = F.readlines ()
Print (date)
F.close ()

#结果:
#[' eray\n ', ' eray\n ', ' bike\n ']
#打印出来的带 \ n, how do you get rid of it?

#解决方法:
#1,
f = open ("Name.txt")
Date = F.read (). Splitlines ()
Print (date)
F.close ()
#结果:
#[' Eray ', ' eray ', ' bike ']

#2,
f = open ("Name.txt")
Date = F.readlines ()
#date = Date.strip (' \ n ')
Date = ". Join (date). strip (' \ n ')
Print (date)
F.close ()
#结果:

Eray
Eray
Bike

In the 2nd, the commented out line

#date = Date.strip (' \ n ') #如果去掉注释, the following error is reported:

Reason:

The message mentions this attribute in list that does not have strip. And we know that strip is a property of the string, stating that F.readlines is returning a list. This can result in an error.

Since F.readlines () returns a list, and strip is a property of a string, it is not difficult to think of the Strip property as long as we convert the list returned by F.readlines () to a string. So how do you convert a list to a string? The Join property of the string is used here.

line = ". Join (line) #这样就将列表转换成字符串了.

such as instances.

Strip function Usage:

Function prototypes

Declaration: S is a string, RM is a sequence of characters to be deleted

S.strip (RM) Remove the characters from the beginning and end of the s string in the RM delete sequence

S.lstrip (RM) Delete the character in the S string at the beginning of the RM delete sequence

S.rstrip (RM) Removes the character from the end of the S string that is located in the RM delete sequence

Attention:

1. When RM is empty, the default is to remove the whitespace characters (including ' \ n ', ' \ R ', ' \ t ', ')

Python:line=f.readlines () How to eliminate the ' \ n ' in line

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.