相关疑难解决方法(0)

懒惰记录器消息字符串评估

我在我的python应用程序中使用标准的python日志记录模块:

import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("log")
while True:
  logger.debug('Stupid log message " + ' '.join([str(i) for i in range(20)]) )
  # Do something

问题是,虽然调试级别不启用,那个愚蠢的日志消息是在每次循环迭代,这严重损害了性能评估.

这有什么解决方案吗?

在C++中,我们有log4cxx一个提供这样的宏的包:
LOG4CXX_DEBUG(logger, messasage)
有效地评估为

if (log4cxx::debugEnabled(logger)) {
    log4cxx.log(logger,log4cxx::LOG4CXX_DEBUG, message)
}

但是由于Python(AFAIK)中没有宏,是否有一种有效的记录方法?

python logging

61
推荐指数
4
解决办法
2万
查看次数

在str.format中切片字符串

我希望通过以下方式实现以下目标str.format:

x,y = 1234,5678
print str(x)[2:] + str(y)[:2]
Run Code Online (Sandbox Code Playgroud)

我能做到的唯一方法是:

print '{0}{1}'.format(str(x)[2:],str(y)[:2])
Run Code Online (Sandbox Code Playgroud)

现在,这个例子和我真正拥有的是一个冗长而凌乱的字符串,所以我想把切片放在里面{}.我研究了文档,但我无法弄清楚正确的语法.我的问题是:是否可以在替换字段内切换字符串?

python string string-formatting

18
推荐指数
2
解决办法
5361
查看次数

如何将变量评估为 Python f 字符串

我想要一种评估 f 字符串的机制,其中要评估的内容在变量中提供。例如,

x=7
s='{x+x}'
fstr_eval(s)
Run Code Online (Sandbox Code Playgroud)

对于我想到的用例,字符串s可能来自用户输入(用户信任的地方eval)。

虽然eval在生产中使用通常是非常糟糕的做法,但也有明显的例外。例如,用户可能是在本地机器上工作的 Python 开发人员,他希望使用完整的 Python 语法来开发 SQL 查询。

关于重复的注意事项:这里这里有类似的问题。第一个问题是在模板的有限上下文中提出的。第二个问题虽然与这个问题非常相似,但已被标记为重复。因为这个问题的上下文与第一个问题有很大不同,我决定根据第二个问题之后自动生成的建议提出第三个问题:

这个问题以前有人问过,已经有了答案。如果这些答案不能完全解决您的问题,请提出一个新问题。

python string-interpolation python-3.x python-3.6 f-string

7
推荐指数
2
解决办法
3338
查看次数

是否可以像使用字符串和格式一样重用f字符串?

我想创建一个f字符串,它可以与以下代码一起多次使用format

TEXT_AMOUNT = 'text {amount}'


def f1(beginning):
    return beginning + TEXT_AMOUNT.format(amount=10)


def f2(ending):
    return TEXT_AMOUNT.format(amount=100) + ending
Run Code Online (Sandbox Code Playgroud)

如何使用f字符串实现相同的功能?我试过了:

TEXT_AMOUNT = f'text {amount}'


def f1(beginning):
    amount = 100
    return beginning + TEXT_AMOUNT


def f2(ending):
    amount = 10
    return TEXT_AMOUNT + ending
Run Code Online (Sandbox Code Playgroud)

但是,出现以下错误:

NameError: name 'amount' is not defined
Run Code Online (Sandbox Code Playgroud)

python python-3.x f-string

3
推荐指数
3
解决办法
1233
查看次数

如何将f字符串与变量一起使用,而不是与字符串文字一起使用?

我想将f-string与我的string变量一起使用,而不是与使用字符串常量定义的string一起使用"..."

这是我的代码

name=["deep","mahesh","nirbhay"]
user_input = r"certi_{element}" # this string i ask from user  

for element in name:
    print(f"{user_input}")
Run Code Online (Sandbox Code Playgroud)

此代码提供输出:

certi_{element}
certi_{element}
certi_{element}
Run Code Online (Sandbox Code Playgroud)

但我想要:

certi_{deep}
certi_{mahesh}
certi_{nirbhay}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

python string string-formatting python-3.x f-string

3
推荐指数
3
解决办法
4024
查看次数

Python:'{0.lower()}'。format('A')产生'str'对象没有属性'lower()'

在Python中,字符串有一个方法lower()

>>> dir('A')
[... 'ljust', 'lower', 'lstrip', ...]
Run Code Online (Sandbox Code Playgroud)

但是,当尝试时'{0.lower()}'.format('A'),响应指出:

>>> '{0.lower()}'.format('A')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'lower()'
Run Code Online (Sandbox Code Playgroud)

有人可以帮助我理解为什么在这种情况下,上面的行会引发AttributeError吗?似乎它不应该是AttributeError,尽管我一定会误会。任何帮助了解这一点将非常欢迎!

编辑:我知道我不能在format调用内调用lower()方法(尽管如果可能的话,它会很整洁);我的问题是为什么这样做会引发AttributeError。在这种情况下,此错误似乎会引起误解。

python attributeerror

3
推荐指数
1
解决办法
320
查看次数

我可以在Python的字符串格式"语言"中进行数学运算吗?

我在做字符串格式化的时候想做一些简单的数学运算.例如

N = {'number':3}
four = '{number:d + 1}'.format(**N)
Run Code Online (Sandbox Code Playgroud)

这当然不起作用.有没有办法实现这一点,我不知道?

谢谢!

python

2
推荐指数
1
解决办法
2377
查看次数

在python中动态解析变量

说我有一个字符串 -

my_str = "From {country} with Love"

变量country目前不可用,稍后将设置为

country = "Russia".

现在我可以用动态解析的内联变量值打印字符串吗?就像是 -

print(f"{my_str}")

这将输出

From Russia with Love

我尝试使用 eval() 但没有帮助。

python dynamic-variables f-string

1
推荐指数
1
解决办法
364
查看次数

使用f字符串作为模板

以前,我用作str.format()模板方法,例如:

template = "Hello, my name is {0} and I'm {1} years old, my favourite colour is {2}"

# Rest of the program...

print(template.format("John", "30", "Red"))
Run Code Online (Sandbox Code Playgroud)

我最近了解了f字符串,我很想知道是否有一种以这种方式使用它的方法。定义模板,并在需要时替换为适当的值,而不是立即评估括号的内容。

python python-3.x f-string

0
推荐指数
1
解决办法
52
查看次数

字符串占位符的更Pythonic方式?

有没有更Pythonic的方法来执行以下操作?F 字符串似乎需要一个定义的变量(没有空表达式),但如果我想稍后定义 @names 和 @locations,最好的方法是什么?

funct_a = call_function()

str_a = f"a very long string of text that contains {funct_a} and also @names or @locations"

... 
large chunk of code that modifies str_a and defines var_a, var_b, var_c, var_d
...

if <conditional>:
    str_b = str_a.replace("@names", var_a).replace("@locations", var_b)
elif <conditional>:
    str_b = str_a.replace("@names", var_c).replace("@locations", var_d)
Run Code Online (Sandbox Code Playgroud)

python

0
推荐指数
1
解决办法
48
查看次数