【问题标题】:Python string operations to generate date formatPython字符串操作生成日期格式
【发布时间】:2021-11-24 01:46:23
【问题描述】:

我正在使用下面的代码来生成一个可以在我的代码中使用的变量: year_current is 21的值

代码:

month_1 = "Jan '"
month_2 = "Dec '"
'"' + month_1 + str(year_current) + '":"' +month_2 + str(year_current) + '"'

以上代码生成的输出为:

"Jan \'21":"Dec \'21"

我不想在输出中出现 "" 符号。可以做些什么来避免这种情况?

预期输出:

"Jan '21":"Dec '21" (with all the quotes intact so that I can use this in df.loc)

我也使用了以下方法:

代码:

month_1 = "'Jan '"
month_2 = ":'Dec '"
month_1 +str(year_current)+"'" +month_2 +str(year_current)+"'"

这给了我输出:

'Jan '21':'Dec '21'

但是它会在代码中对单引号造成混淆。因此这对我不起作用。

不确定是不是因为我的代码在 Jupyter 中,但解决方案没有按预期工作:

【问题讨论】:

  • @Downvote:为什么要投反对票?请解释一下,以便我将来改进。

标签: python pandas string


【解决方案1】:

在这种情况下,您可以使用f-string

试试这个:

month_1 = "Jan '"
month_2 = "Dec '"
year_current = 21
#year_current = pd.Timestamp.today().strftime('%y') #if you dont want hardcord year

month_str = f'"{month_1}{year_current}":"{month_2}{year_current}"'

print(month_str)

输出:

"Jan '21":"Dec '21"

【讨论】:

  • 打印将显示没有反斜杠的输出。但是当我在代码中使用month_str变量时,它将包含“\”
  • 能否请您分享您正在工作的代码,以便我们也可以进行测试?
  • 我刚刚从您的回答中删除了打印声明。请检查没有打印语句的month_str的值。
  • 你能试试我更新的答案吗?
  • 我在上面的问题中发布了截图。不确定是不是因为 Jupyter notebook。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多