给定字符串的python中的base转换 [英] Base convert in python given a string

查看:95
本文介绍了给定字符串的python中的base转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中,给定一个字符串值(用字符分隔的整数),我们可以计算其整数表示形式:

In PHP, given a string value (integers separated by chars), we can calculate its integer representation:

$hashable = "123A123"; // notice "A" delim
$hash_int = base_convert($hashable, 11, 10);
echo $hash_int;

输出

2151042

这很有用,因为结果对于大范围的字符串(当然是短字符串)是唯一的.我在应用程序中将其用于生成ID.

It's useful because result is unique for huge range of strings (short ones, of course). I use it for ID generation in my application.

我们如何在python中进行相同的转换?是否可以在PHP和python中为相同的字符串生成相等的整数?

How can we do same conversions in python? Is it possible to generate equal integers for same strings in both PHP and python?

也许首先我们需要将 hash int 提取为hashable string ,然后转换整数的基数,但是我们到底是怎么做到的呢?

Maybe first we need to take hash int of hashable string and then convert the base of integer but how exactly we do this?

推荐答案

以前建议的方法将因二进制和许多其他转换而失败,此方法将从2的任何基数变为36,并根据 php实现,除非您输入无效的字符,否则php实现不会忽略输出中的字母输入基数,然后它会尝试查找数字并进行转换,因此您也无法尽可能地返回int值,并且会在输出中得到字母:

Previously suggested method will fail for binary and many other conversions, this will go from any base from 2 to 36 and return 0 for invalid strings as per the php implementation, the php implementation does not ignore letters in the output unless you give invalid input for the base and then it tries to find just the digits and convert so you also cannot return an int as you can and will get letters in the output:

def to_base(n, bse):
    digs = "0123456789abcdefghijklmnopqrstuvwxyz"
    tmp = []
    while n:
        n, i = divmod(n, bse)
        tmp.append(digs[i])
    return "".join(tmp[::-1])



def chng_frm_base(s, frm_bse, to_bse):
    if to_bse < 2 or to_bse > 36 or frm_bse < 2 or frm_bse > 36:
        raise ValueError("bases must be between 2-36")
    try:
        return to_base(int(s, frm_bse), to_bse)
    except ValueError:
        try:
            n = int("".join([ch for ch in s if ch.isdigit()]),frm_bse)
            return to_base(n, to_bse)
        except ValueError:
            return 0

输出:

In [13]: chng_frm_base("123A123", 11, 10)
Out[13]: '2151042'

In [14]: chng_frm_base("123A123", 11, 8)
Out[14]: '10151202'

In [15]: chng_frm_base("123A123", 11, 2)
Out[15]: '1000001101001010000010'

In [16]: chng_frm_base("123A123", 11, 35)
Out[16]: '1f5xc'

In [17]: chng_frm_base("123A123", 11, 1)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-17-9776e0abca26> in <module>()
----> 1 chng_frm_base("123A123", 11, 1)

<ipython-input-2-9c00d800545d> in chng_frm_base(s, frm_bse, to_bse)
     10 def chng_frm_base(s, frm_bse, to_bse):
     11     if to_bse < 2 or to_bse > 36 or frm_bse < 2 or frm_bse > 36:
---> 12         raise ValueError("bases must be between 2-36")
     13     try:
     14         return (to_base(int(s, frm_bse), to_bse))

ValueError: bases must be between 2-36

In [18]: chng_frm_base("hello world!", 10, 2)
Out[18]: 0

如果您使用php运行相同的示例,则会为所有输出相同的值.

Which if you run the same examples using php outputs the same values for all.

这篇关于给定字符串的python中的base转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆