简体   繁体   English

如何获取 python 中每一行的第一个字母?

[英]How to get first letter of each line in python?

here is what I got txt and open txt file looks like这是我得到的 txt 和打开的 txt 文件看起来像

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

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

output But I would like to get this output但我想得到这个

['C\n','D\n','C\n','D\n'........] ['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.首先,您需要以读取模式打开文件( r标志为open ),然后您可以使用 for 循环遍历文件 object 以一次读取每一行。 Lastly, you want to access the first element of each line at index 0 to get the first letter.最后,您要访问索引 0 处每行的第一个元素以获取第一个字母。

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:如果您想让换行符仍然出现在字符串中,您可以将第 5 行从上面修改为:

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

    f.close() 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 获取python中每个2个字母的单词的第一个字母 - Get the first letter of each 2-letter word in python 如何在Python中获取第一个大写字母,然后再获取每个不跟另一个大写字母的字母? - How to get the first capital letter and then each that isn't followed by another capital letter in Python? 如何将 python 中每个单词的首字母大写? - How to capitalize the First letter of each word in python? (python):在每个点之后拆分为新行,并在保留点的情况下将每行的每个首字母大写 - (python): split after each dot into a new line and capitalize each first letter of each line with keeping the dots Python 在每一行打印字母 - Python is printing letter on each line Python 新手:如何保持每个单词的首字母大写? - New to Python: How to keep the first letter of each word capitalized? Python 2.7:如何查找字符串中每个单词的第一个字母的索引 - Python 2.7: how to find the index of the first letter of each word in a string 使用正则表达式将每行的第一个字母大写 - capitalize first letter of each line using regex 如何获取dataframe列的字符串中每个单词的首字母 - How to get the first letter of each word in a string of dataframe column 如何打印 python 中每个字符串的第一个字母、第二个字母和第三个字母? - How do I print the first letter and second letter and third.. of each string in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM