在Python中从字符串中打印一个单词
我想知道怎么在Python中只打印字符串中的某些单词。比如,我想打印第三个单词(是个数字)和第十个单词。
而且每次文本的长度可能都不一样。
mystring = "You have 15 new messages and the size is 32000"
谢谢。
6 个回答
4
看起来你是在对比程序的输出结果或者日志文件。
在这种情况下,你需要找到足够的信息来确保你匹配的是正确的内容,但又不能匹配得太死板,以免输出稍微有点变化时你的程序就出错。
正则表达式在这种情况下非常有效,比如:
>>> import re
>>> mystring = "You have 15 new messages and the size is 32000"
>>> match = re.search(r"(\d+).*?messages.*?size.*?(\d+)", mystring)
>>> if not match: print "log line didn't match"
...
>>> messages, size = map(int, match.groups())
>>> messages
15
>>> size
32000
4
mystring = "You have 15 new messages and the size is 32000"
print mystring.split(" ")[2] #Prints the 3rd word
print mystring.split(" ")[9] #Prints the 10th word
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。
8
mystring = "You have 15 new messages and the size is 32000"
parts = mystring.split(' ')
message_count = int(parts[2])
message_size = int(parts[9])
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。