How to get first letter of each line in python?

Viewed 42

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'........]

2 Answers

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() 
Related