简体   繁体   中英

How to get first letter of each line in python?

here is what I got txt and open txt file looks like

f = open('data.txt', 'r')
print(f.read())

the show['Cat\n','Dog\n','Cat\n','Dog\n'........]

output But I would like to get this

['C\n','D\n','C\n','D\n'........]

First you'll want to open the file in read mode ( r flag in open ), then you can iterate through the file object with a for loop to read each line one at a time. Lastly, you want to access the first element of each line at index 0 to get the first letter.

first_letters = []

with open('data.txt', 'r') as f:
    for line in f:
        first_letters.append(line[0])

print(first_letters)

If you want to have the newline character still present in the string you can modify line 5 from above to:

first_letters.append(line[0] + '\n')
    f = open("data.txt", "r")
    
    for x in f:
      print(x[0]) 

    f.close() 

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