【问题标题】:inserting variables into "b" bytes将变量插入“b”字节
【发布时间】:2012-09-02 20:40:50
【问题描述】:

这是我当前的代码:

 encodedstring = base64.encodestring(b"admin:password")[:-1]

现在我想为用户名和密码使用变量,像这样?

  username = "admin"
  password = "password"
  user_pass = username + ":" + password

  user_pass = b"user_pass <<<<?
  encodedstring = base64.encodestring(user_pass)[:-1]

我该怎么做?

非常感谢

【问题讨论】:

  • bytes(user_pass, 'ascii') 不做吗?还是user_pass.encode('ascii')?选择你喜欢的任何编码。
  • 是的,bytes(user_pass, 'ascii') 做同样的伎俩。谢谢。

标签: python-3.x base64 byte


【解决方案1】:

嗯,像这样吗?

username = b"admin"
password = b"password"
user_pass = username + b":" + password

encodedstring = base64.encodestring(user_pass)[:-1]

或者你是说用户名和密码来自某个给你字符串的地方?

在这种情况下对它们进行编码。

username = get_username().encode('UTF8')
password = get_password().encode('UTF8')
user_pass = username + b":" + password

使用 UTF-8 以便非 ascii 字符也能正常工作。

【讨论】:

    【解决方案2】:
    base64.b64encode((user + ':' + password).encode('utf-8'))
    

    【讨论】:

    • 这个也有效:base64.b64encode((user + ':' + password).encode('utf-8')) ,非常感谢大家。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-06
    • 1970-01-01
    • 2017-03-18
    • 1970-01-01
    • 2012-10-18
    • 1970-01-01
    相关资源
    最近更新 更多