#!/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