简体   繁体   English

我试图弄清楚如何根据 python 中的特定字符在用户输入的字符串中打印特定单词

[英]I am trying to figure out how to print specific words in a string inputted by the user based on a specific character in python

For instance, if the user entered "Hello welcome to the code" and the program was looking for the character 'e' the program would print: Hello welcome the code例如,如果用户输入“Hello welcome to the code”并且程序正在寻找字符'e',程序将打印:Hello welcome the code

This looks like a honework assignment... if thats the case, please keep in mind that if u dont understand the basics and u dont try to understand it, you will never learn it... also, SO is here to help u with your problem, when u get stuck by getting somekinda error or something... right now all u did is nothing and u r just crying for help... but I have a good more, so here is the code that does it (u should know how to ha dle input;))这看起来像是一项功课……如果是这样,请记住,如果您不了解基础知识并且不尝试理解它,那么您将永远学不会...此外,SO 可以帮助您您的问题,当您因遇到某种错误或某事而陷入困境时...现在您所做的一切都是徒劳的,而您 r 只是在寻求帮助...但我还有更多,所以这是执行此操作的代码(您应该知道如何处理输入;))

inp = "Bla bla bla bla tra tra tea"
inp2 = "r"
words = inp.split(" ")
for w in words:
    if inp2 in w:
        print(w)

Also u need to fix formatting (this eill print each word to a different line;)... if u have any other questions, please let me know:)您还需要修复格式(这将每个单词打印到不同的行;)...如果您有任何其他问题,请告诉我:)

It seems like you want to print all words that contain a specific letter.似乎您想打印所有包含特定字母的单词。 Just split the string on the spaces then either remove all the words that don't have the char or add those that do to a new list then join the list on a space to recombine it.只需在空格上拆分字符串,然后删除所有没有字符的单词,或者将具有字符的单词添加到新列表中,然后在空格上加入列表以重新组合它。 This approach does assume there is are spaces between each word not tabs or newlines (you can just remove the ' ' from the split to split on whitespace but this approach always reassembles the good words using single spaces.这种方法确实假设每个单词之间有空格而不是制表符或换行符(您可以从拆分中删除 ' ' 以拆分空格,但这种方法总是使用单个空格重新组合好单词。

words = line.split(' ')
goodWords = []
for word in words:
    if word.find(keyChar) != -1:
        goodWords.append(word)
goodLine = ' '.join(goodWords)

Just use the.split function, it will split each individual word up into an array list so that you can individually assess each word.只需使用.split function,它将每个单词拆分为一个数组列表,以便您可以单独评估每个单词。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM