Python 如何从字段[0]中选择一个字母,从字段[1]中选择全名?

Python 如何从字段[0]中选择一个字母,从字段[1]中选择全名?,python,Python,以下是我希望做的事 我希望从字段[0]中选择一个字母,并从字段[1]中选择全名 以下是我迄今为止所取得的成就 file = open("songs.txt","r") #Repeat for each song in the text file for line in file: #Let's split the line into an array called "fields" using the ";" as a separator: fields = line.split("

以下是我希望做的事

我希望从字段[0]中选择一个字母,并从字段[1]中选择全名

以下是我迄今为止所取得的成就

file = open("songs.txt","r")

#Repeat for each song in the text file
for line in file:

  #Let's split the line into an array called "fields" using the ";" as a separator:
  fields = line.split(";")

  #and let's extract the data:
  songTitle = fields[0]
  artist = fields[1]

  #Print the song
  print(songTitle + " by " + artist)

#It is good practice to close the file at the end to free up resources   
file.close()
这是一个示例

这是songs.txt文件

神的计划;德雷克
翁贝拉;蕾哈娜
完美的埃德·希兰
你的形状;埃德·希兰
你好阿黛勒
接下来谢谢你;阿丽亚娜·格兰德
爱你自己;贾斯汀·比伯
自信;黛米·洛瓦托
对不起不对不起;黛米·洛瓦托
回到你身边;赛琳娜·戈麦斯
哈瓦那;卡米拉·卡贝罗
我喜欢它;心脏b
朱曼吉;B杨
玛丽亚;库姆兹


python
和大多数编程语言中,可以嵌套具有索引的对象。我的意思是,一个列表可以包含列表,可以包含列表,可以包含字符串。为了访问字符串中的字母,需要在每个嵌套列表中提供索引,然后在字符串中提供索引。所以对于一个名为
lololos
的字符串列表列表:
lolos
是一个字符串列表列表
lololos[0]
是字符串列表
lololos[0][0]
是字符串列表
lololos[0][0][0]
是一个字符串;而
lololos[0][0][0][0]
是一个字母

当你
.split
一个字符串时,你会得到一个字符串列表。因此,
fields=line.split(;”)
实际上是一个包含两个字符串的列表。因此,
字段[0]
是一个字符串<代码>字段[0][0]是第一个字符串的第一个字母

file = open("songs.txt","r")

#Repeat for each song in the text file
for line in file:

  #Let's split the line into an array called "fields" using the ";" as a separator:
  fields = line.split(";")

  #and let's extract the data:
  songTitle = fields[0]
  artist = fields[1]
  songTitleFirstChar = fields[0][0]

  #Print the song
  print(songTitleFirstChar + " by " + artist)

#It is good practice to close the file at the end to free up resources   
file.close()

欢迎来到SO,请阅读并编辑您的问题Hello Laiba。你的问题细节还不够!但是我猜你想要的是:打印(字段[0][0]+字段[1])我想打印第一个字段中的一个字母,意思是来自歌曲,然后是来自第二个字段的艺术家的全名。我不知道如何选择第一个字母try@abdullah.cu。如果不是解决方案,请提供示例中预期的输出