I have saved a list of ticker symbols into a text file as follows:
MMM ABT ABBV ANF ....
Then I use readlines to put the symbols into a Python list:
stocks = open(textfile).readlines()
However, when I look at the list in it contains Windows end-of-line delimiter which I do not want:
list: ['MMM\r\n', 'ABT\r\n', 'ABBV\r\n', 'ANF\r\n', 'ACE\r\n', 'ACN\r\n', 'ACT\r\n', 'ADBE\r\n', 'ADT\r\n', 'AMD\r\n', 'AES\r\n', .....
Can someone suggest the easiest way to remove these unwanted characters?
You can use str. strip . '\r' is a carriage return, and strip removes leading and trailing whitespace and new line characters.
Use the str. rstrip() method to remove \r\n from a string in Python, e.g. result = my_str. rstrip() .
Method 2: Use the strip() Function to Remove a Newline Character From the String in Python. The strip() method in-built function of Python is used to remove all the leading and trailing spaces from a string. Our task can be performed using strip function() in which we check for “\n” as a string in a string.
In addition to the for loop, Python provides three methods to read data from the input file. The readline method reads one line from the file and returns it as a string. The string returned by readline will contain the newline character at the end.
That's basically how readlines
works. You could post-process it:
stocks = [x.rstrip() for x in stocks]
But I prefer not using readlines
at all if I don't want EOL character(s), instead doing:
stocks = open(textfile).read().splitlines()
Or even better:
with open(textfile) as f: stocks = f.read().splitlines()
(it almost certainly won't make a difference here, but using context managers to explicitly close file objects is a good habit to get into)
readlines()
should never be used unless you know that the file is really small. For your application, it is better to use rstrip()
with open(filename, 'r') as f: for l in f: l = l.rstrip() # other operations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With