如何将所有参数转换为字符串格式的字符串

发布于 2024-12-10 01:54:06 字数 1373 浏览 0 评论 0原文

从 Corey Goldberg 的这个开始:

#!/usr/bin/env python

import json
import pprint
import urllib2


def get_stock_quote(ticker_symbol):   
    url = 'http://finance.google.com/finance/info?q=%s' % ticker_symbol
    lines = urllib2.urlopen(url).read().splitlines()
    return json.loads(''.join([x for x in lines if x not in ('// [', ']')]))


if __name__ == '__main__':
    quote = get_stock_quote('IBM')
    print 'ticker: %s' % quote['t']
    print 'current price: %s' % quote['l_cur']
    print 'last trade: %s' % quote['lt']
    print 'full quote:'
    pprint.pprint(quote)

使用这个:

import urllib2, json

def get_stock_quote(ticker_symbol):   
    url = 'http://finance.google.com/finance/info?q=%s' % ticker_symbol
    lines = urllib2.urlopen(url).read().splitlines()
    #print lines
    return json.loads(''.join([x for x in lines if x not in ('// [', ']')]))



if __name__ == '__main__':
    symbols = ('Goog',) 
    symbols2 = ('Goog','MSFT')
    quote = get_stock_quote(symbols)
    print 'ticker: %s' % quote['t'],  'current price: %s' % quote['l_cur'], 'last trade: %s' % quote['ltt']
    print quote['t'],  quote['l'], quote['ltt']

使用符号有效,符号2无效。错误消息为

TypeError:在字符串格式化期间未转换所有参数

如何将所有参数转换为字符串格式中的字符串。在浏览器中,有效的代码是:Goog,MSFT。

编辑:我正在寻找的输出是一个包含 goog、msft 信息的列表。

Starting with this from Corey Goldberg:

#!/usr/bin/env python

import json
import pprint
import urllib2


def get_stock_quote(ticker_symbol):   
    url = 'http://finance.google.com/finance/info?q=%s' % ticker_symbol
    lines = urllib2.urlopen(url).read().splitlines()
    return json.loads(''.join([x for x in lines if x not in ('// [', ']')]))


if __name__ == '__main__':
    quote = get_stock_quote('IBM')
    print 'ticker: %s' % quote['t']
    print 'current price: %s' % quote['l_cur']
    print 'last trade: %s' % quote['lt']
    print 'full quote:'
    pprint.pprint(quote)

Using this:

import urllib2, json

def get_stock_quote(ticker_symbol):   
    url = 'http://finance.google.com/finance/info?q=%s' % ticker_symbol
    lines = urllib2.urlopen(url).read().splitlines()
    #print lines
    return json.loads(''.join([x for x in lines if x not in ('// [', ']')]))



if __name__ == '__main__':
    symbols = ('Goog',) 
    symbols2 = ('Goog','MSFT')
    quote = get_stock_quote(symbols)
    print 'ticker: %s' % quote['t'],  'current price: %s' % quote['l_cur'], 'last trade: %s' % quote['ltt']
    print quote['t'],  quote['l'], quote['ltt']

Usings symbols works, symbols2 does not work. The error message is

TypeError: not all arguments converted during string formatting

How do I convert all arguments to string in string formatting. In browser, the code that works is: Goog,MSFT.

EDIT: the output I am looking for is a list with goog, msft info.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

情栀口红 2024-12-17 01:54:06

您的问题是 %s 无法处理包含 2 个元素的元组,请参阅下面的示例:

>>> "=%s" % ('Goog',)
'=Goog'
>>> "=%s" % ('Goog','MSFT')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting

无论如何,请使用 format() 而不是 %

Your problem is that %s can't handle a tuple with 2 elements, see that example below:

>>> "=%s" % ('Goog',)
'=Goog'
>>> "=%s" % ('Goog','MSFT')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting

Anyway, use format() instead of %.

想念有你 2024-12-17 01:54:06

在这种情况下,您可以:

import urllib2, json

def get_stock_quote(ticker_symbol):
    if isinstance(ticker_symbol, (list, tuple)):
        ticker_symbol = ','.join(ticker_symbol)
    url = 'http://finance.google.com/finance/info?q=%s' % ticker_symbol
    lines = urllib2.urlopen(url).read().splitlines()
    #print lines
    return json.loads('[%s]' % ''.join([x for x in lines if x not in ('// [', ']')]))

if __name__ == '__main__':
    symbols = ('Goog',) 
    symbols2 = ('Goog','MSFT')
    quotes = get_stock_quote(symbols2)
    for quote in quotes:
        print 'ticker: %s' % quote['t'],  'current price: %s' % quote['l_cur'], 'last trade: %s' % quote['ltt']
        print quote['t'],  quote['l'], quote['ltt']

In this case you can make:

import urllib2, json

def get_stock_quote(ticker_symbol):
    if isinstance(ticker_symbol, (list, tuple)):
        ticker_symbol = ','.join(ticker_symbol)
    url = 'http://finance.google.com/finance/info?q=%s' % ticker_symbol
    lines = urllib2.urlopen(url).read().splitlines()
    #print lines
    return json.loads('[%s]' % ''.join([x for x in lines if x not in ('// [', ']')]))

if __name__ == '__main__':
    symbols = ('Goog',) 
    symbols2 = ('Goog','MSFT')
    quotes = get_stock_quote(symbols2)
    for quote in quotes:
        print 'ticker: %s' % quote['t'],  'current price: %s' % quote['l_cur'], 'last trade: %s' % quote['ltt']
        print quote['t'],  quote['l'], quote['ltt']
伴梦长久 2024-12-17 01:54:06

您收到此错误是因为格式化只需要一个字符串,而您将元组放入 2 个字符串。如果您想获取 http://finance.google.com/finance/info? q=Goog,MSFT 你应该这样做

quote = get_stock_quote(",".join(['Goog','MSFT']))

或者循环执行此操作:

for symbol in ('Goog', 'MSFT'):
    quote = get_stock_quote(symbol)

You got this error because formatting require only one string, while you put tuple with 2 strings. If you want to get http://finance.google.com/finance/info?q=Goog,MSFT you should do

quote = get_stock_quote(",".join(['Goog','MSFT']))

Or do this in cycle:

for symbol in ('Goog', 'MSFT'):
    quote = get_stock_quote(symbol)
那小子欠揍 2024-12-17 01:54:06

问题就在这里:

url = 'http://finance.google.com/finance/info?q=%s' % ticker_symbol

使用 symbols2,您提供的是 2 元组,而格式化运算符需要标量或 1 元组。

以下内容将修复立即错误:

url = 'http://finance.google.com/finance/info?q=%s' % ",".join(ticker_symbol)

这只能解决一半的问题:解析结果的代码也需要更改。我将其作为练习留给读者。

The problem is here:

url = 'http://finance.google.com/finance/info?q=%s' % ticker_symbol

With symbols2, you're supplying a 2-tuple whereas the formatting operator expects a scalar or a 1-tuple.

The following will fix the immediate error:

url = 'http://finance.google.com/finance/info?q=%s' % ",".join(ticker_symbol)

This only fixes half of the problem: the code that parses the results will also need to change. I leave this as an exercise for the reader.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文