我正在使用常规redis包来将我的Python代码连接到我的Redis服务器.
作为我的代码的一部分,我检查我的Redis服务器密钥中是否存在字符串对象.
string = 'abcde'
if string in redis.keys():
do something..
Run Code Online (Sandbox Code Playgroud)
出于某些原因,redis.keys()返回一个包含字节对象的列表,例如[b'abcde'],而我的字符串当然是一个str对象.
我已经尝试设置charset,encoding并decode_responses在我的redis生成器中,但它没有帮助.
我的目标是将数据作为字符串向前插入,而不是遍历键列表并在检查时将每个元素更改为str().
谢谢你
我几年前使用的是先前提出的问题的代码,但我相信这已经过时了.试图运行代码,我收到上面的错误.我仍然是python的新手,所以我无法从类似的问题中得到很多澄清.任何人都知道为什么会这样吗?
import subprocess
def getLength(filename):
result = subprocess.Popen(["ffprobe", filename],
stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
return [x for x in result.stdout.readlines() if "Duration" in x]
print(getLength('bell.mp4'))
Run Code Online (Sandbox Code Playgroud)
追溯
Traceback (most recent call last):
File "B:\Program Files\ffmpeg\bin\test3.py", line 7, in <module>
print(getLength('bell.mp4'))
File "B:\Program Files\ffmpeg\bin\test3.py", line 6, in getLength
return [x for x in result.stdout.readlines() if "Duration" in x]
File "B:\Program Files\ffmpeg\bin\test3.py", line 6, in <listcomp>
return [x for x in result.stdout.readlines() if "Duration" in x]
TypeError: a …Run Code Online (Sandbox Code Playgroud) 如何将内存zipfile写入文件?
# Create in memory zip and add files
zf = zipfile.ZipFile(StringIO.StringIO(), mode='w',compression=zipfile.ZIP_DEFLATED)
zf.writestr('file1.txt', "hi")
zf.writestr('file2.txt', "hi")
# Need to write it out
f = file("C:/path/my_zip.zip", "w")
f.write(zf) # what to do here? Also tried f.write(zf.read())
f.close()
zf.close()
Run Code Online (Sandbox Code Playgroud) 我在使用Unicode的Python中遇到了问题.我需要在其中绘制带有Unicode注释的图形.根据教程我应该用Unicode创建我的字符串.我是这样做的:
annotation = u"%s has %s rev"%(art.title, len(art.revisions))
Run Code Online (Sandbox Code Playgroud)
它art.title有Unicode字符.有时代码有效,有时会给我以下错误:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 19: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
我该如何解决?
编辑:我在"注释"行后完全有错误:
File "script.py", line 195, in test_trie
annotation = u"%s has %s rev"%(art.title, len(art.revisions))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 19: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud) 我知道对于Python <3,字符串'Plants vs. Zombies‰2'的unicode编码如下:
u"Plants vs. Zombies䋢 2".encode("utf-8")
Run Code Online (Sandbox Code Playgroud)
如果我有一个变量(比如appName)而不是字符串,我可以这样做:
appName = "Plants vs. Zombies䋢 2"
u+appName.encode("utf-8")
Run Code Online (Sandbox Code Playgroud)
对于:
appName = appName.encode('utf-8');
'ascii' codec can't decode byte 0xe4 in position 18: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud) 我正在使用mac anaconda.我尝试使用加密的AES.但是,我面临一个奇怪的问题.
我只是想执行一行简单的代码:
obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
Run Code Online (Sandbox Code Playgroud)
如果我在没有虚拟环境的情况下运行代码,则可以.
$ python
Python 3.6.4 |Anaconda, Inc.| (default, Jan 16 2018, 12:04:33)
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin
Type "help", "copyright", "credits" or "license" for more
information.
>>> from Crypto.Cipher import AES
>>> obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
Run Code Online (Sandbox Code Playgroud)
如果我运行虚拟环境"testaes"然后我得到错误:
(testaes)$ python
Python 3.6.4 |Anaconda, Inc.| (default, Mar 12 2018, 20:05:31)
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin …Run Code Online (Sandbox Code Playgroud) 我正在尝试加密和解密python中的文本,我知道该怎么做 - 问题是我不想使用一定数量的字母,如16或32.我希望能够使用尽可能多的字母/数字,然后加密文本没有任何错误.
python中的base64会很完美,因为我可以做到这一点,但是当我想做的时候:
password = "password"
encode = base64.b64encode(password)
Run Code Online (Sandbox Code Playgroud)
...它返回一个错误,因为它不是以字节为单位; 它必须像:
encode = base64.b64encode(b'password')
Run Code Online (Sandbox Code Playgroud)
这完全没问题,但我不想这样做.
import base64
password = "hello world"
encoded = base64.b64encode(password.encode("utf-8"))
print(encoded)
decoded = base64.b64decode(encoded)
print(decoded)
Run Code Online (Sandbox Code Playgroud)
这是现在我的代码,它工作正常,但我现在知道我正在使用错误的类型,我需要知道如何使用AES.
我试图转换一个字符串,其中包含需要多个十六进制值的字符,如下所示:
'Mahou Shoujo Madoka\xe2\x98\x85Magica'
Run Code Online (Sandbox Code Playgroud)
到它的unicode表示:
'Mahou Shoujo Madoka?Magica'
Run Code Online (Sandbox Code Playgroud)
当我打印字符串时,它会尝试分别评估每个十六进制值,所以默认情况下我得到这个:
x = 'Mahou Shoujo Madoka\xe2\x98\x85Magica'
print(x)
Mahou Shoujo MadokaâMagica
Run Code Online (Sandbox Code Playgroud)
所以我尝试了其他一些StackOverflow答案,例如在Python 3中将字符串转换为字节的最佳方法?:
x = 'Mahou Shoujo Madoka\xe2\x98\x85Magica'
z = x.encode('utf-8')
print('z:', z)
y = z.decode('utf-8')
print('y:', y)
z: b'Mahou Shoujo Madoka\xc3\xa2\xc2\x98\xc2\x85Magica'
y: Mahou Shoujo MadokaâMagica
Run Code Online (Sandbox Code Playgroud)
Python:将Unicode-Hex-String转换为Unicode:
z = 'Mahou Shoujo Madoka\xe2\x98\x85Magica'
x = binascii.unhexlify(binascii.hexlify(z.encode('utf-8'))).decode('utf-8')
print('x:', x)
x: Mahou Shoujo MadokaâMagica
Run Code Online (Sandbox Code Playgroud)
还有一些,但没有一个有效.我发现的大部分结果都是有双反斜杠问题的人,但没有一个人有我的确切问题.
我注意到当我执行str.encode时,它似乎在二进制中添加了一些额外的值(例如第一次尝试中z和x之间的差异),我不太清楚为什么.
所以我尝试在二进制文件中手动输入字符串的字符:
x = b'Mahou Shoujo Madoka\xe2\x98\x85Magica'
x.decode('utf-8')
'Mahou Shoujo Madoka?Magica'
Run Code Online (Sandbox Code Playgroud)
它起作用了.但是除了输入外,我找不到从字符串转换为字符串的方法.我哪里错了?
我有以下函数可以从字节序列中解析 utf-8 字符串
注意 -- 'length_size' 是表示 utf-8 字符串长度所需的字节数
def parse_utf8(self, bytes, length_size):
length = bytes2int(bytes[0:length_size])
value = ''.join(['%c' % b for b in bytes[length_size:length_size+length]])
return value
def bytes2int(raw_bytes, signed=False):
"""
Convert a string of bytes to an integer (assumes little-endian byte order)
"""
if len(raw_bytes) == 0:
return None
fmt = {1:'B', 2:'H', 4:'I', 8:'Q'}[len(raw_bytes)]
if signed:
fmt = fmt.lower()
return struct.unpack('<'+fmt, raw_bytes)[0]
Run Code Online (Sandbox Code Playgroud)
我想反过来写这个函数——即一个函数,它将接受一个 utf-8 编码的字符串,并将它的表示作为一个字节字符串返回。
到目前为止,我有以下几点:
def create_utf8(self, utf8_string):
return utf8_string.encode('utf-8')
Run Code Online (Sandbox Code Playgroud)
我在尝试测试时遇到以下错误:
File "writer.py", line 229, in create_utf8 …Run Code Online (Sandbox Code Playgroud) 我试图创建一个程序,采取用户输入,而不是显示实际输入我想用*替换输入
我已经尝试使用此代码,但我不断收到下面的错误,我将不胜感激任何指导或帮助.
import msvcrt
import sys
def userinput(prompt='>'):
write = sys.stdout.write
for x in prompt:
msvcrt.putch(x)
entry = ""
while 1:
x = msvcrt.getch()
print(repr(x))
if x == '\r' or x == '\n':
break
if x == '\b':
entry = entry[:-1]
else:
write('*')
entry = entry + x
return entry
userEntry = userinput()
Run Code Online (Sandbox Code Playgroud)
错误:
Traceback (most recent call last):
File "C:\Users\Mehdi\Documents\Teaching\KS5\AS CS\getPass.py", line 24, in <module>
userEntry = userinput()
File "C:\Users\Mehdi\Documents\Teaching\KS5\AS CS\getPass.py", line 9, in userinput
msvcrt.putch(x)
TypeError: putch() argument …Run Code Online (Sandbox Code Playgroud)