选择多个单词的第一个字母

2024-10-01 04:56:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要显示多个单词的第一个字母,这些单词是从列表中的多个项目中收集的

尝试收集列表项,使用word.split(" ")song[0][0/1]将它们分开

for word in song:
    songWords = word.split(" ")
    songLetter1 = songWords[0][0]
    songLetter2 = songWords[1][0]
    print("")
    print("The artist is", artist, "and the first letter of the song is", 
           songWord1, songWord2)

希望是“s”和一个数字,取决于随机选择的项目


Tags: the项目in列表forsongartistis
2条回答

如果输入是列表

song=["hey","lol"]
for word in song:
    songWords = word.split(" ")
    songWord1 = songWords[0][0]
    print("")
    print("The artist is and the first letter of the song is",songWord1)

从.txt文件中读取文本后,可以将其存储在字符串中。我假设字符串看起来像下面的宋体。你知道吗

尝试:

songText = "song 1, song 2"
songs = songText.split(",")
print(songs)
artist = "artist 1"
for song in songs:
    song = song.strip() # To remove spaces before and after the text.
    songWords = song.split(" ")
    # The below lines will work assuming there are at least two words in the song.
    songLetter1 = songWords[0][0]
    songLetter2 = songWords[1][0]
    print("")
    print("The artist is", artist, "and the first letter of the song is", 
           songLetter1, songLetter2)

希望这有帮助!你知道吗

相关问题 更多 >