Python: line = f. readlines () method to remove \ n in line, pythonf. readlines
Test code
#!/ust/bin/env python3f = open("name.txt")date = f.readlines()print(date)f.close()
# Result:
# ['Eray \ n', 'eray \ n', 'bike \ n']
# How do I remove the printed \ n?
# Solution:
#1,
f = open("name.txt")date = f.read().splitlines()print(date)f.close()
# Result:
# ['Eray', 'eray', 'bike']
#2,
f = open("name.txt")date = f.readlines()#date = date.strip('\n')date = ''.join(date).strip('\n')print(date)f.close()
# Result:
Eray
Eray
Bike
This line commented out in 2nd
# Date = date. strip ('\ n') # If the comment is removed, the following error is returned:
Cause:
The prompt indicates that the list does not have this attribute of strip. As we know, strip is a string attribute, indicating that f. readlines returns a list. Therefore, errors may occur.
Since f. readlines () returns a list and strip is a string attribute, it is hard to think that we can use the strip attribute as long as we convert the list returned by f. readlines () to a string. So how to convert the list to a string? The join attribute of the string is used here.
line = ''.join(line)
# Convert the list to a string.
1st, directly using the string method: splitlines
For example:
Usage of the strip function:
Function prototype
Declaration: "s" is a string and "rm" is the sequence of characters to be deleted.
S. strip (rm) Delete the characters starting and ending in the s string and located in the rm Delete Sequence
S. lstrip (rm) Delete the characters starting from the s string in the rm Delete Sequence
S. rstrip (rm) deletes the characters at the end of the s string in the rm deletion sequence.
Note:
1. When rm is blank, blank spaces (including '\ n',' \ R', '\ t', '') are deleted by default ','')
Ask yourself how to move bricks every day.
Add:
#-*-Coding: UTF-8-*-# open the file fo = open ("jb51.txt", "r") print ("file name:", fo. name) for line in fo. readlines (): # Read line = line in sequence. strip () # Remove the blank print at the beginning and end of each line ("read data: % s" % (line) # close the file fo. close ()
Line = line. strip () is to remove the leading and trailing spaces of each line.