简体   繁体   中英

Python: Stripping elements of a string array based on first character of each element

First, I'm reading a text file into a string array. Then I'm removing newline from each element once they're loaded in the array. These steps work fine. Finally, I'd like to filter out any elements in the string array that aren't filenames (beginning with "/").

I'm wondering if I can achieve this using the same type of syntax used for stripping newline, ie "file_array = [word.strip() for word in file_array]"

Code Excerpt:

# read file into string array
with open(bom_filename, 'r') as my_file:
    file_array = my_file.readlines()

# remove newline from strings
file_array = [word.strip() for word in file_array]

# filter out records that are not filenames
file_array = [if word[0]=="/" for word in file_array]  <= could I do something like this?

Although this syntax is really useful, I'm not very familiar with it! Can conditional statements be used in it?

Thanks in advance...

with open(bom_filename, 'r') as my_file:
    file_array = [word.strip() for word in my_file if word.startswith("/")]

No need to call .readlines()

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM