【问题标题】:How to use quotation marks and full stops in Python function argument如何在 Python 函数参数中使用引号和句号
【发布时间】:2020-12-22 14:59:51
【问题描述】:

我似乎无法在 Python 中使用这种格式。我正在尝试定义一个包含表单参数的函数 - “[Some].[Name]”

谁能告诉我我是怎么做到的?我想我已经尝试了 ' 和 " 的所有组合,但不管论点中的 [.] 和 ["] 似乎都不起作用。

在下面的代码中,我试图将参数定义为“VWS.co”

def get_stock_data(Company):
    #This function defines the data to be collected.
    #send a get request to query Company's end of day stock prices in period
    global VWS_data
    Stock_data = yf.Ticker(Company)
    Stock_data = Stock_data.history(period="5y")
    # look at the first 5 rows of the dataframe
    print(Stock_data)
    print(Stock_data.describe(include='all'))

get_stock_data("VWS.co")

编辑: 使用转义字符 get_stock_data(""VWS.co"") 使定义生效。但是,还是有些不对劲。当我运行脚本时,它仍然只能使用“VWS.co”作为定义。请参见下面的代码, VWS_data_with_arg 有效。 VWS_data 没有。我在这里遗漏了一些非常明显的东西吗?

def get_stock_data(Company):
    Stock_data = yf.Ticker("VWS.co")
    Stock_data_with_arg = yf.Ticker(Company)
    VWS_data = Stock_data.history(period="5y")
    VWS_data_with_arg = Stock_data_with_arg.history(period="5y")
    print(VWS_data) #This returns the expected values
    print(VWS_data_with_arg) #This returns an empty dataset

get_stock_data("\"VWS.co\"")

【问题讨论】:

  • get_stock_data('"VWS.co"') 会帮你的!

标签: python function format arguments


【解决方案1】:

你应该使用转义字符。

get_stock_data("\"VWS.co\"")

【讨论】:

  • 谢谢,这解决了我认为的问题。但是,它仍然无法正常工作。当我删除参数并在语句中插入“VMS.co”时,它就起作用了。但是,当我使用转义字符时,它无法定义 VMS_data,我确实尝试打印 Company 并且它按预期定义。我还在函数顶部添加了语句“global VWS_data”,仍然没有运气。有什么想法吗?
【解决方案2】:

你可以使用原始字符串

get_stock_data(r'"VWS.co"')

【讨论】:

  • 字符串中没有任何内容需要原始字符串文字。 '"VWS.co"' 产生相同的值。
猜你喜欢
  • 2020-03-14
  • 2019-10-05
  • 2015-10-06
  • 2017-04-18
  • 2020-08-12
  • 1970-01-01
  • 2015-06-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多