如何在python中仅打印字符串中的特定单词?假设我只想打印第三个单词(这是一个数字)和第十个单词
而文本长度每次都可能不同
mystring = "You have 15 new messages and the size is 32000"
谢谢。
发布于 2010-05-16 02:14:32
mystring = "You have 15 new messages and the size is 32000"
parts = mystring.split(' ')
message_count = int(parts[2])
message_size = int(parts[9])发布于 2010-05-16 02:23:34
看起来您正在匹配程序输出或日志文件中的内容。
在这种情况下,您希望进行足够的匹配,以便有信心匹配正确的内容,但不要太多,以至于如果输出稍有变化,程序就会出错。
正则表达式在这种情况下工作得很好,例如
>>> 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发布于 2010-05-16 07:56:16
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 wordhttps://stackoverflow.com/questions/2841165
复制相似问题