I have a textfile where I want to extract the first word, but without the first character and put it into a list. Is there a way in python to do this without using regex? A text example of what I have looks like:
#blabla sjhdiod jszncoied
Where I want the first word in this case blabla without the #. If regex is the only choice, then how will the regex look like?
This should do the trick:
l = []
for line in open('file'):
l.append(line.split()[0][1:])
Edit: If you have empty lines, this will throw an error. You will have to check for empty lines. Here is a possible solution:
l = []
for line in open('file'):
if line.strip():
l.append(line.split()[0][1:])
Python方式:
my_list = [line.split(' ', 1)[0][1:] for line in open('file') if line.startswith('#')]
a textfile where I want to extract the first word , but without the first character and put it into a list
result = []
with open('file.txt', 'r') as f:
l = next(f).strip() # getting the 1st line
result.append(l[1:l.find(' ')])
print(result)
The output:
['blabla']
Simple enough if your input is so regular:
s = "#blabla sjhdiod jszncoied"
s.split()[0].strip('#')
blabla
split
splits on whitespace by default. Take the first token and strip away '#'
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.