query
stringlengths 9
60
| language
stringclasses 1
value | code
stringlengths 105
25.7k
| url
stringlengths 91
217
|
---|---|---|---|
convert int to string | python | def string_to_int( s ):
"""Convert a string of bytes into an integer, as per X9.62."""
result = 0
for c in s:
if not isinstance(c, int): c = ord( c )
result = 256 * result + c
return result | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/ecdsa/ecdsa.py#L169-L175 |
convert int to string | python | def to_int(s):
""" converts a string to an integer
>>> to_int('1_000_000')
1000000
>>> to_int('1e6')
1000000
>>> to_int('1000')
1000
"""
try:
return int(s.replace('_', ''))
except ValueError:
return int(ast.literal_eval(s)) | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/cli.py#L8-L23 |
convert int to string | python | def _string_to_int(self, string):
"""
Convert a string to a number, using the given alphabet..
"""
number = 0
for char in string[::-1]:
number = number * self._alpha_len + self._alphabet.index(char)
return number | https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/extern/shortuuid/__init__.py#L30-L37 |
convert int to string | python | def int_to_string( x ):
"""Convert integer x into a string of bytes, as per X9.62."""
assert x >= 0
if x == 0: return b('\0')
result = []
while x:
ordinal = x & 0xFF
result.append(int2byte(ordinal))
x >>= 8
result.reverse()
return b('').join(result) | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/ecdsa/ecdsa.py#L155-L166 |
convert int to string | python | def string_to_num(s: str):
"""Converts a string to an int/float
Returns ``None`` if it can't be converted
>>> string_to_num('5')
5
>>> string_to_num('5.2')
5.2
>>> string_to_num(10)
10
>>> string_to_num(10.1)
10.1
>>> string_to_num('this is not a string') is None
True
"""
if isinstance(s, (int, float)):
return s
if s.isdigit():
return int(s)
try:
return float(s)
except ValueError:
return None | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/utils/core.py#L148-L171 |
convert int to string | python | def str2int(self, num):
"""Converts a string into an integer.
If possible, the built-in python conversion will be used for speed
purposes.
:param num: A string that will be converted to an integer.
:rtype: integer
:raise ValueError: when *num* is invalid
"""
radix, alphabet = self.radix, self.alphabet
if radix <= 36 and alphabet[:radix].lower() == BASE85[:radix].lower():
return int(num, radix)
ret = 0
lalphabet = alphabet[:radix]
for char in num:
if char not in lalphabet:
raise ValueError("invalid literal for radix2int() with radix "
"%d: '%s'" % (radix, num))
ret = ret * radix + self.cached_map[char]
return ret | https://github.com/django-treebeard/django-treebeard/blob/8042ee939cb45394909237da447f8925e3cc6aa3/treebeard/numconv.py#L83-L105 |
convert int to string | python | def convert_string(string):
"""Convert string to int, float or bool.
"""
if is_int(string):
return int(string)
elif is_float(string):
return float(string)
elif convert_bool(string)[0]:
return convert_bool(string)[1]
elif string == 'None':
return None
else:
return string | https://github.com/theislab/scanpy/blob/9e4e5ee02e04cf618872d9b098e24f0542e8b227/scanpy/readwrite.py#L602-L614 |
convert int to string | python | def ints_to_string(ints):
"""Convert a list of integers to a *|* separated string.
Args:
ints (list[int]|int): List of integer items to convert or single
integer to convert.
Returns:
str: Formatted string
"""
if not isinstance(ints, list):
return six.u(str(ints))
return '|'.join(six.u(str(l)) for l in ints) | https://github.com/rmed/pyemtmad/blob/c21c42d0c7b50035dfed29540d7e64ab67833728/pyemtmad/util.py#L123-L136 |
convert int to string | python | def string_to_int(string, alphabet):
"""
Convert a string to a number, using the given alphabet.
The input is assumed to have the most significant digit first.
"""
number = 0
alpha_len = len(alphabet)
for char in string:
number = number * alpha_len + alphabet.index(char)
return number | https://github.com/skorokithakis/shortuuid/blob/4da632a986c3a43f75c7df64f27a90bbf7ff8039/shortuuid/main.py#L25-L34 |
convert int to string | python | def _char2int(char):
""" translate characters to integer values (upper and lower case)"""
if char.isdigit():
return int(float(char))
if char.isupper():
return int(char, 36)
else:
return 26 + int(char, 36) | https://github.com/mommermi/callhorizons/blob/fdd7ad9e87cac107c1b7f88e594d118210da3b1a/callhorizons/callhorizons.py#L46-L53 |
convert int to string | python | def str_to_int_array(string, base=16):
"""
Converts a string to an array of integer values according to the
base specified (int numbers must be whitespace delimited).\n
Example: "13 a3 3c" => [0x13, 0xa3, 0x3c]
:return: [int]
"""
int_strings = string.split()
return [int(int_str, base) for int_str in int_strings] | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/libutils.py#L23-L33 |
convert int to string | python | def fast_int(
x,
key=lambda x: x,
_uni=unicodedata.digit,
_first_char=POTENTIAL_FIRST_CHAR,
):
"""
Convert a string to a int quickly, return input as-is if not possible.
We don't need to accept all input that the real fast_int accepts because
natsort is controlling what is passed to this function.
Parameters
----------
x : str
String to attempt to convert to an int.
key : callable
Single-argument function to apply to *x* if conversion fails.
Returns
-------
*str* or *int*
"""
if x[0] in _first_char:
try:
return long(x)
except ValueError:
try:
return _uni(x, key(x)) if len(x) == 1 else key(x)
except TypeError: # pragma: no cover
return key(x)
else:
try:
return _uni(x, key(x)) if len(x) == 1 else key(x)
except TypeError: # pragma: no cover
return key(x) | https://github.com/SethMMorton/natsort/blob/ea0d37ef790b42c424a096e079edd9ea0d5717e3/natsort/compat/fake_fastnumbers.py#L89-L125 |
convert int to string | python | def to_string(x):
"""
Utf8 conversion
:param x:
:return:
"""
if isinstance(x, bytes):
return x.decode('utf-8')
if isinstance(x, basestring):
return x | https://github.com/crocs-muni/roca/blob/74ad6ce63c428d83dcffce9c5e26ef7b9e30faa5/roca/detect.py#L306-L315 |
convert int to string | python | def int_to_string(number, alphabet, padding=None):
"""
Convert a number to a string, using the given alphabet.
The output has the most significant digit first.
"""
output = ""
alpha_len = len(alphabet)
while number:
number, digit = divmod(number, alpha_len)
output += alphabet[digit]
if padding:
remainder = max(padding - len(output), 0)
output = output + alphabet[0] * remainder
return output[::-1] | https://github.com/skorokithakis/shortuuid/blob/4da632a986c3a43f75c7df64f27a90bbf7ff8039/shortuuid/main.py#L9-L22 |
convert int to string | python | def int_convert(base):
'''Convert a string to an integer.
The string may start with a sign.
It may be of a base other than 10.
If may start with a base indicator, 0#nnnn, which we assume should
override the specified base.
It may also have other non-numeric characters that we can ignore.
'''
CHARS = '0123456789abcdefghijklmnopqrstuvwxyz'
def f(string, match, base=base):
if string[0] == '-':
sign = -1
else:
sign = 1
if string[0] == '0' and len(string) > 2:
if string[1] in 'bB':
base = 2
elif string[1] in 'oO':
base = 8
elif string[1] in 'xX':
base = 16
else:
# just go with the base specifed
pass
chars = CHARS[:base]
string = re.sub('[^%s]' % chars, '', string.lower())
return sign * int(string, base)
return f | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/parse.py#L462-L496 |
convert int to string | python | def toString(value):
"""
Convert a value to a string, if possible.
"""
if isinstance(value, basestring):
return value
elif type(value) in [np.string_, np.str_]:
return str(value)
elif type(value) == np.unicode_:
return unicode(value)
else:
raise TypeError("Could not convert %s to string type" % type(value)) | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/ml/param/__init__.py#L202-L213 |
convert int to string | python | def convert_to_int(value):
"""Attempts to convert a specified value to an integer
:param value: Content to be converted into an integer
:type value: string or int
"""
if not value:
return None
# Apart from numbers also accept values that end with px
if isinstance(value, str):
value = value.strip(' px')
try:
return int(value)
except (TypeError, ValueError):
return None | https://github.com/michaelhelmick/lassie/blob/b929f78d7e545cff5fb42eb5edfcaf396456f1ee/lassie/utils.py#L31-L48 |
convert int to string | python | def to_int(value: str) -> int:
"""
Robust to integer conversion, handling hex values, string representations,
and special cases like `0x`.
"""
if is_0x_prefixed(value):
if len(value) == 2:
return 0
else:
return int(value, 16)
else:
return int(value) | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/_utils/normalization.py#L105-L116 |
convert int to string | python | def conv_to_float(indata, inf_str=''):
"""Try to convert an arbitrary string to a float. Specify what will be replaced with "Inf".
Args:
indata (str): String which contains a float
inf_str (str): If string contains something other than a float, and you want to replace it with float("Inf"),
specify that string here.
Returns:
float: Converted string representation
"""
if indata.strip() == inf_str:
outdata = float('Inf')
else:
try:
outdata = float(indata)
except:
raise ValueError('Unable to convert {} to float'.format(indata))
return outdata | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/utils.py#L854-L874 |
convert int to string | python | def _to_string(val):
"""Convert to text."""
if isinstance(val, binary_type):
return val.decode('utf-8')
assert isinstance(val, text_type)
return val | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/hash.py#L31-L36 |
convert int to string | python | def _convert_name(self, name):
"""Convert ``name`` to int if it looks like an int.
Otherwise, return it as is.
"""
if re.search('^\d+$', name):
if len(name) > 1 and name[0] == '0':
# Don't treat strings beginning with "0" as ints
return name
return int(name)
return name | https://github.com/PSU-OIT-ARC/django-local-settings/blob/758810fbd9411c2046a187afcac6532155cac694/local_settings/settings.py#L251-L262 |
convert int to string | python | def int2str(self, num):
"""Converts an integer into a string.
:param num: A numeric value to be converted to another base as a
string.
:rtype: string
:raise TypeError: when *num* isn't an integer
:raise ValueError: when *num* isn't positive
"""
if int(num) != num:
raise TypeError('number must be an integer')
if num < 0:
raise ValueError('number must be positive')
radix, alphabet = self.radix, self.alphabet
if radix in (8, 10, 16) and \
alphabet[:radix].lower() == BASE85[:radix].lower():
return ({8: '%o', 10: '%d', 16: '%x'}[radix] % num).upper()
ret = ''
while True:
ret = alphabet[num % radix] + ret
if num < radix:
break
num //= radix
return ret | https://github.com/django-treebeard/django-treebeard/blob/8042ee939cb45394909237da447f8925e3cc6aa3/treebeard/numconv.py#L56-L81 |
convert int to string | python | def to_int(value=None, hexstr=None, text=None):
"""
Converts value to it's integer representation.
Values are converted this way:
* value:
* bytes: big-endian integer
* bool: True => 1, False => 0
* hexstr: interpret hex as integer
* text: interpret as string of digits, like '12' => 12
"""
assert_one_val(value, hexstr=hexstr, text=text)
if hexstr is not None:
return int(hexstr, 16)
elif text is not None:
return int(text)
elif isinstance(value, bytes):
return big_endian_to_int(value)
elif isinstance(value, str):
raise TypeError("Pass in strings with keyword hexstr or text")
else:
return int(value) | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/_utils/encoding.py#L118-L141 |
convert int to string | python | def bin_to_int(string):
"""Convert a one element byte string to signed int for python 2 support."""
if isinstance(string, str):
return struct.unpack("b", string)[0]
else:
return struct.unpack("b", bytes([string]))[0] | https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/utils.py#L71-L76 |
convert int to string | python | def int_0_inf(cls, string):
'''Convert string to int.
If ``inf`` is supplied, it returns ``0``.
'''
if string == 'inf':
return 0
try:
value = int(string)
except ValueError as error:
raise argparse.ArgumentTypeError(error)
if value < 0:
raise argparse.ArgumentTypeError(_('Value must not be negative.'))
else:
return value | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/options.py#L104-L120 |
convert int to string | python | def to_inttuple(bitstr):
"""Convert from bit string likes '01011' to int tuple likes (0, 1, 0, 1, 1)
Args:
bitstr (str, Counter, dict): String which is written in "0" or "1".
If all keys are bitstr, Counter or dict are also can be converted by this function.
Returns:
tuple of int, Counter, dict: Converted bits.
If bitstr is Counter or dict, returns the Counter or dict
which contains {converted key: original value}.
Raises:
ValueError: If bitstr type is unexpected or bitstr contains illegal character.
"""
if isinstance(bitstr, str):
return tuple(int(b) for b in bitstr)
if isinstance(bitstr, Counter):
return Counter({tuple(int(b) for b in k): v for k, v in bitstr.items()})
if isinstance(bitstr, dict):
return {tuple(int(b) for b in k): v for k, v in bitstr.items()}
raise ValueError("bitstr type shall be `str`, `Counter` or `dict`") | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/utils.py#L18-L39 |
convert int to string | python | def bigint_to_string(val):
""" Converts @val to a string if it is a big integer (|>2**53-1|)
@val: #int or #float
-> #str if @val is a big integer, otherwise @val
"""
if isinstance(val, _NUMBERS) and not abs(val) <= 2**53-1:
return str(val)
return val | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/tools/strings.py#L91-L100 |
convert int to string | python | def convert_int(value, parameter):
'''
Converts to int or float:
'', '-', None convert to parameter default
Anything else uses int() or float() constructor
'''
value = _check_default(value, parameter, ( '', '-', None ))
if value is None or isinstance(value, int):
return value
try:
return int(value)
except Exception as e:
raise ValueError(str(e)) | https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/converter/converters.py#L41-L53 |
convert int to string | python | def _asString(self, value):
"""converts the value as a string"""
if sys.version_info[0] == 3:
if isinstance(value, str):
return value
elif isinstance(value, bytes):
return value.decode('utf-8')
elif sys.version_info[0] == 2:
return value.encode('ascii') | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/web/_base.py#L533-L541 |
convert int to string | python | def to_int(value: str, default: T = None) -> Union[int, Optional[T]]:
"""Convert given value to int.
If conversion failed, return default value without raising Exception.
:param value: Value to convert to int.
:param default: Default value to use in case of failed conversion.
"""
try:
return int(value)
except (TypeError, ValueError):
return default | https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/utils.py#L35-L46 |
convert int to string | python | def str_digit_to_int(chr):
"""
Converts a string character to a decimal number.
Where "A"->10, "B"->11, "C"->12, ...etc
Args:
chr(str): A single character in the form of a string.
Returns:
The integer value of the input string digit.
"""
# 0 - 9
if chr in ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"):
n = int(chr)
else:
n = ord(chr)
# A - Z
if n < 91:
n -= 55
# a - z or higher
else:
n -= 61
return n | https://github.com/squdle/baseconvert/blob/26c9a2c07c2ffcde7d078fb812419ca6d388900b/baseconvert/baseconvert.py#L452-L474 |
convert int to string | python | def _to_string(x):
"""Convert to a unicode string.
If x is a byte string, assume it is utf-8 and decode to a Python unicode
string. You must call this on text strings you get back from libvips.
"""
if x == ffi.NULL:
x = 'NULL'
else:
x = ffi.string(x)
if isinstance(x, byte_type):
x = x.decode('utf-8')
return x | https://github.com/libvips/pyvips/blob/f4d9334d2e3085b4b058129f14ac17a7872b109b/pyvips/error.py#L33-L47 |
convert int to string | python | def tostring(self, encoding):
""" quote the string if not encoded
else encode and return """
if self.kind == 'string':
if encoding is not None:
return self.converted
return '"{converted}"'.format(converted=self.converted)
elif self.kind == 'float':
# python 2 str(float) is not always
# round-trippable so use repr()
return repr(self.converted)
return self.converted | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/computation/pytables.py#L584-L595 |
convert int to string | python | def convert_number(string):
"""Convert a string to number
If int convert to int otherwise float
If not possible return None
"""
res = None
if isint(string):
res = int(string)
elif isfloat(string):
res = float(string)
return res | https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scout/utils/convert.py#L24-L35 |
convert int to string | python | def to_int(value, default=0):
"""
Tries to convert the value passed in as an int. If no success, returns the
default value passed in
:param value: the string to convert to integer
:param default: the default fallback
:return: int representation of the value passed in
"""
try:
return int(value)
except (TypeError, ValueError):
return to_int(default, default=0) | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/utils/__init__.py#L779-L790 |
convert int to string | python | def string_to_integer(value, strict=False):
"""
Return an integer corresponding to the string representation of a
number.
@param value: a string representation of an integer number.
@param strict: indicate whether the specified string MUST be of a
valid integer number representation.
@return: the integer value represented by the string.
@raise ValueError: if the string doesn't represent a valid integer,
while the argument ``strict`` equals ``True``.
"""
if is_undefined(value):
if strict:
raise ValueError('The value cannot be null')
return None
try:
return int(value)
except ValueError:
raise ValueError('The specified string "%s" does not represent an integer' % value) | https://github.com/dcaune/perseus-lib-python-common/blob/ba48fe0fd9bb4a75b53e7d10c41ada36a72d4496/majormode/perseus/utils/cast.py#L256-L280 |
convert int to string | python | def _isint(string):
"""
>>> _isint("123")
True
>>> _isint("123.45")
False
"""
return type(string) is int or \
(isinstance(string, _binary_type) or isinstance(string, _text_type)) and \
_isconvertible(int, string) | https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/extern/tabulate.py#L254-L263 |
convert int to string | python | def parse_int_token(token):
"""
Parses a string to convert it to an integer based on the format used:
:param token:
The string to convert to an integer.
:type token:
``str``
:return:
``int`` or raises ``ValueError`` exception.
Usage::
>>> parse_int_token("0x40")
64
>>> parse_int_token("040")
32
>>> parse_int_token("40")
40
>>> parse_int_token("foobar")
Traceback (most recent call last):
...
ValueError: invalid literal for int() with base 10: 'foobar'
"""
if token.startswith("0x") or token.startswith("0X"):
return int(token, 16)
elif token.startswith("0"):
return int(token, 8)
else:
return int(token) | https://github.com/gorakhargosh/pepe/blob/1e40853378d515c99f03b3f59efa9b943d26eb62/pepe/__init__.py#L457-L486 |
convert int to string | python | def to_int(
primitive: Primitives = None, hexstr: HexStr = None, text: str = None
) -> int:
"""
Converts value to its integer representation.
Values are converted this way:
* primitive:
* bytes, bytearrays: big-endian integer
* bool: True => 1, False => 0
* hexstr: interpret hex as integer
* text: interpret as string of digits, like '12' => 12
"""
if hexstr is not None:
return int(hexstr, 16)
elif text is not None:
return int(text)
elif isinstance(primitive, (bytes, bytearray)):
return big_endian_to_int(primitive)
elif isinstance(primitive, str):
raise TypeError("Pass in strings with keyword hexstr or text")
elif isinstance(primitive, (int, bool)):
return int(primitive)
else:
raise TypeError(
"Invalid type. Expected one of int/bool/str/bytes/bytearray. Got "
"{0}".format(type(primitive))
) | https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/conversions.py#L46-L74 |
convert int to string | python | def NonNegIntStringToInt(int_string, problems=None):
"""Convert an non-negative integer string to an int or raise an exception"""
# Will raise TypeError unless a string
match = re.match(r"^(?:0|[1-9]\d*)$", int_string)
# Will raise ValueError if the string can't be parsed
parsed_value = int(int_string)
if parsed_value < 0:
raise ValueError()
elif not match and problems is not None:
# Does not match the regex, but it's an int according to Python
problems.InvalidNonNegativeIntegerValue(int_string)
return parsed_value | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/util.py#L501-L514 |
convert int to string | python | def _to_number(cls, string):
"""Convert string to int or float."""
try:
if float(string) - int(string) == 0:
return int(string)
return float(string)
except ValueError:
try:
return float(string)
except ValueError:
return string | https://github.com/dgomes/pyipma/blob/cd808abeb70dca0e336afdf55bef3f73973eaa71/pyipma/api.py#L35-L45 |
convert int to string | python | def parse_int(v, header_d):
"""Parse as an integer, or a subclass of Int."""
v = nullify(v)
if v is None:
return None
try:
# The converson to float allows converting float strings to ints.
# The conversion int('2.134') will fail.
return int(round(float(v), 0))
except (TypeError, ValueError) as e:
raise CastingError(int, header_d, v, 'Failed to cast to integer') | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/valuetype/types.py#L127-L140 |
convert int to string | python | def _convert_string_to_unicode(string):
"""
If the string is bytes, decode it to a string (for python3 support)
"""
result = string
try:
if string is not None and not isinstance(string, six.text_type):
result = string.decode('utf-8')
except (TypeError, UnicodeDecodeError, AttributeError):
# Sometimes the string actually is binary or StringIO object,
# so if you can't decode it, just give up.
pass
return result | https://github.com/kevin1024/vcrpy/blob/114fcd29b43c55896aaa6a6613bc7766f2707c8b/vcr/serializers/compat.py#L40-L54 |
convert int to string | python | def ints2str(self, int_values):
"""Conversion list[int] => decoded string."""
if not self._encoder:
raise ValueError(
"Text.ints2str is not available because encoder hasn't been defined.")
return self._encoder.decode(int_values) | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/text_feature.py#L90-L95 |
convert int to string | python | def to_utf8(s):
"""Convert a string to utf8. If the argument is an iterable
(list/tuple/set), then each element of it would be converted instead.
>>> to_utf8('a')
'a'
>>> to_utf8(u'a')
'a'
>>> to_utf8([u'a', u'b', u'\u4f60'])
['a', 'b', '\\xe4\\xbd\\xa0']
"""
if six.PY2:
if isinstance(s, str):
return s
elif isinstance(s, unicode):
return s.encode('utf-8')
elif isinstance(s, (list, tuple, set)):
return [to_utf8(v) for v in s]
else:
return s
else:
return s | https://github.com/lins05/slackbot/blob/7195d46b9e1dc4ecfae0bdcaa91461202689bfe5/slackbot/utils.py#L27-L48 |
convert int to string | python | def int_to_decimal_str(integer):
"""
Helper to convert integers (representing cents) into decimal currency
string. WARNING: DO NOT TRY TO DO THIS BY DIVISION, FLOATING POINT
ERRORS ARE NO FUN IN FINANCIAL SYSTEMS.
@param integer The amount in cents
@return string The amount in currency with full stop decimal separator
"""
int_string = str(integer)
if len(int_string) < 2:
return "0." + int_string.zfill(2)
else:
return int_string[:-2] + "." + int_string[-2:] | https://github.com/raphaelm/python-sepaxml/blob/187b699b1673c862002b2bae7e1bd62fe8623aec/sepaxml/utils.py#L64-L76 |
convert int to string | python | def _integerValue_to_int(value_str):
"""
Convert a value string that conforms to DSP0004 `integerValue`, into
the corresponding integer and return it. The returned value has Python
type `int`, or in Python 2, type `long` if needed.
Note that DSP0207 and DSP0004 only allow US-ASCII decimal digits. However,
the Python `int()` function supports all Unicode decimal digits (e.g.
US-ASCII digits, ARABIC-INDIC digits, superscripts, subscripts) and raises
`ValueError` for non-decimal digits (e.g. Kharoshthi digits).
Therefore, the match patterns explicitly check for US-ASCII digits, and
the `int()` function should never raise `ValueError`.
Returns `None` if the value string does not conform to `integerValue`.
"""
m = BINARY_VALUE.match(value_str)
if m:
value = int(m.group(1), 2)
elif OCTAL_VALUE.match(value_str):
value = int(value_str, 8)
elif DECIMAL_VALUE.match(value_str):
value = int(value_str)
elif HEX_VALUE.match(value_str):
value = int(value_str, 16)
else:
value = None
return value | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/_utils.py#L316-L342 |
convert int to string | python | def num(string):
"""convert a string to float"""
if not isinstance(string, type('')):
raise ValueError(type(''))
try:
string = re.sub('[^a-zA-Z0-9\.\-]', '', string)
number = re.findall(r"[-+]?\d*\.\d+|[-+]?\d+", string)
return float(number[0])
except Exception as e:
logger = logging.getLogger('tradingAPI.utils.num')
logger.debug("number not found in %s" % string)
logger.debug(e)
return None | https://github.com/federico123579/Trading212-API/blob/0fab20b71a2348e72bbe76071b81f3692128851f/tradingAPI/utils.py#L33-L45 |
convert int to string | python | def _isint(string):
"""
>>> _isint("123")
True
>>> _isint("123.45")
False
"""
return type(string) is int or \
(isinstance(string, _binary_type) or
isinstance(string, string_types)) and \
_isconvertible(int, string) | https://github.com/solvebio/solvebio-python/blob/b29614643043afd19c1d8074e8f25c6700d51a73/solvebio/utils/tabulate.py#L160-L170 |
convert int to string | python | def decimal_str_to_int(decimal_string):
"""
Helper to decimal currency string into integers (cents).
WARNING: DO NOT TRY TO DO THIS BY CONVERSION AND MULTIPLICATION,
FLOATING POINT ERRORS ARE NO FUN IN FINANCIAL SYSTEMS.
@param string The amount in currency with full stop decimal separator
@return integer The amount in cents
"""
int_string = decimal_string.replace('.', '')
int_string = int_string.lstrip('0')
return int(int_string) | https://github.com/raphaelm/python-sepaxml/blob/187b699b1673c862002b2bae7e1bd62fe8623aec/sepaxml/utils.py#L79-L89 |
convert int to string | python | def parse_int(value):
"""
Parse numeric string to int. Supports oct formatted string.
:param str value: String value to parse as int
:return int:
"""
value = parse_str(value=value)
if value.startswith("0"):
return int(value.lstrip("0o"), 8)
else:
return int(value) | https://github.com/5monkeys/django-bananas/blob/cfd318c737f6c4580036c13d2acf32bca96654bf/bananas/environment.py#L57-L68 |
convert int to string | python | def charset_to_int(s, charset):
""" Turn a string into a non-negative integer.
>>> charset_to_int('0', B40_CHARS)
0
>>> charset_to_int('10', B40_CHARS)
40
>>> charset_to_int('abcd', B40_CHARS)
658093
>>> charset_to_int('', B40_CHARS)
0
>>> charset_to_int('muneeb.id', B40_CHARS)
149190078205533
>>> charset_to_int('A', B40_CHARS)
Traceback (most recent call last):
...
ValueError: substring not found
"""
output = 0
for char in s:
output = output * len(charset) + charset.index(char)
return output | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/b40.py#L68-L90 |
convert int to string | python | def to_string(type):
"""
Converts a TypeCode into its string name.
:param type: the TypeCode to convert into a string.
:return: the name of the TypeCode passed as a string value.
"""
if type == None:
return "unknown"
elif type == TypeCode.Unknown:
return "unknown"
elif type == TypeCode.String:
return "string"
elif type == TypeCode.Integer:
return "integer"
elif type == TypeCode.Long:
return "long"
elif type == TypeCode.Float:
return "float"
elif type == TypeCode.Double:
return "double"
elif type == TypeCode.Duration:
return "duration"
elif type == TypeCode.DateTime:
return "datetime"
elif type == TypeCode.Object:
return "object"
elif type == TypeCode.Enum:
return "enum"
elif type == TypeCode.Array:
return "array"
elif type == TypeCode.Map:
return "map"
else:
return "unknown" | https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/convert/TypeConverter.py#L166-L201 |
convert int to string | python | def parse_int(s):
""" Parse a string as an integer.
Exit with a message on failure.
"""
try:
val = int(s)
except ValueError:
print_err('\nInvalid integer: {}'.format(s))
sys.exit(1)
return val | https://github.com/welbornprod/fmtblock/blob/92a5529235d557170ed21e058e3c5995197facbe/fmtblock/__main__.py#L180-L189 |
convert int to string | python | def int_to_str_digit(n):
"""
Converts a positive integer, to a single string character.
Where: 9 -> "9", 10 -> "A", 11 -> "B", 12 -> "C", ...etc
Args:
n(int): A positve integer number.
Returns:
The character representation of the input digit of value n (str).
"""
# 0 - 9
if n < 10:
return str(n)
# A - Z
elif n < 36:
return chr(n + 55)
# a - z or higher
else:
return chr(n + 61) | https://github.com/squdle/baseconvert/blob/26c9a2c07c2ffcde7d078fb812419ca6d388900b/baseconvert/baseconvert.py#L477-L496 |
convert int to string | python | def c_str(string):
""""Convert a python string to C string."""
if not isinstance(string, str):
string = string.decode('ascii')
return ctypes.c_char_p(string.encode('utf-8')) | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/amalgamation/python/mxnet_predict.py#L40-L44 |
convert int to string | python | def element_to_int(element, attribute=None):
"""Convert ``element`` object to int. If attribute is not given, convert ``element.text``.
:param element: ElementTree element
:param attribute: attribute name
:type attribute: str
:returns: integer
:rtype: int
"""
if attribute is not None:
return int(element.get(attribute))
else:
return int(element.text) | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/xml_helper.py#L111-L123 |
convert int to string | python | def _ConvertInteger(value):
"""Convert an integer.
Args:
value: A scalar value to convert.
Returns:
The integer value.
Raises:
ParseError: If an integer couldn't be consumed.
"""
if isinstance(value, float) and not value.is_integer():
raise ParseError('Couldn\'t parse integer: {0}.'.format(value))
if isinstance(value, six.text_type) and value.find(' ') != -1:
raise ParseError('Couldn\'t parse integer: "{0}".'.format(value))
return int(value) | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L651-L669 |
convert int to string | python | def _convert_to_numeric(item):
"""
Helper method to convert a string to float or int if possible.
If the conversion is not possible, it simply returns the string.
"""
if PY3:
num_types = (int, float)
else: # pragma: no cover
num_types = (int, long, float) # noqa: F821
# We don't wan't to perform any conversions if item is already a number
if isinstance(item, num_types):
return item
# First try for an int conversion so that strings like "5" are converted
# to 5 instead of 5.0 . This is safe as a direct int cast for a non integer
# string raises a ValueError.
try:
num = int(to_unicode(item))
except ValueError:
try:
num = float(to_unicode(item))
except ValueError:
return item
else:
return num
except TypeError:
return item
else:
return num | https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/utils.py#L11-L40 |
convert int to string | python | def to_bytes(value, encoding='utf-8'):
"""Converts a string value to bytes, if necessary.
Unfortunately, ``six.b`` is insufficient for this task since in
Python 2 because it does not modify ``unicode`` objects.
Args:
value (Union[str, bytes]): The value to be converted.
encoding (str): The encoding to use to convert unicode to bytes.
Defaults to "utf-8".
Returns:
bytes: The original value converted to bytes (if unicode) or as
passed in if it started out as bytes.
Raises:
ValueError: If the value could not be converted to bytes.
"""
result = (value.encode(encoding)
if isinstance(value, six.text_type) else value)
if isinstance(result, six.binary_type):
return result
else:
raise ValueError('{0!r} could not be converted to bytes'.format(value)) | https://github.com/googleapis/google-auth-library-python/blob/2c6ad78917e936f38f87c946209c8031166dc96e/google/auth/_helpers.py#L82-L105 |
convert int to string | python | def _to_int(value_str, min_value, rep_digit, field_name, dtarg):
"""
Convert value_str into an integer, replacing right-consecutive
asterisks with rep_digit, and an all-asterisk value with min_value.
field_name and dtarg are passed only for informational purposes.
"""
if '*' in value_str:
first = value_str.index('*')
after = value_str.rindex('*') + 1
if value_str[first:after] != '*' * (after - first):
raise ValueError(
_format("Asterisks in {0} field of CIM datetime value "
"{1!A} are not consecutive: {2!A}",
field_name, dtarg, value_str))
if after != len(value_str):
raise ValueError(
_format("Asterisks in {0} field of CIM datetime value "
"{1!A} do not end at end of field: {2!A}",
field_name, dtarg, value_str))
if rep_digit is None: # pylint: disable=no-else-return
# Must be an all-asterisk field
if first != 0:
raise ValueError(
_format("Asterisks in {0} field of CIM datetime value "
"{1!A} do not start at begin of field: {2!A}",
field_name, dtarg, value_str))
return min_value
else:
value_str = value_str.replace('*', rep_digit)
# Because the pattern and the asterisk replacement mechanism already
# ensure only decimal digits, we expect the integer conversion to
# always succeed.
value = int(value_str)
return value | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_types.py#L457-L491 |
convert int to string | python | def StrToInt(input_string, bitlength):
"""
Return True if the concrete value of the input_string ends with suffix
otherwise false.
:param input_string: the string we want to transform in an integer
:param bitlength: bitlength of the bitvector representing the index of the substring
:return BVV: bit-vector representation of the integer resulting from ythe string or -1 in bitvector representation
if the string cannot be transformed into an integer
"""
try:
return BVV(int(input_string.value), bitlength)
except ValueError:
return BVV(-1, bitlength) | https://github.com/angr/claripy/blob/4ed61924880af1ea8fb778047d896ec0156412a6/claripy/strings.py#L123-L137 |
convert int to string | python | def string(v):
"""Convert a value to a string."""
if nodesetp(v):
if not v:
return u''
return string_value(v[0])
elif numberp(v):
if v == float('inf'):
return u'Infinity'
elif v == float('-inf'):
return u'-Infinity'
elif str(v) == 'nan':
return u'NaN'
elif int(v) == v and v <= 0xffffffff:
v = int(v)
return unicode(v)
elif booleanp(v):
return u'true' if v else u'false'
return v | https://github.com/gabrielfalcao/dominic/blob/a42f418fc288f3b70cb95847b405eaf7b83bb3a0/dominic/xpath/expr.py#L93-L111 |
convert int to string | python | def to_int(self, number, default=0):
"""Returns an integer
"""
try:
return int(number)
except (KeyError, ValueError):
return self.to_int(default, 0) | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/idserver/view.py#L115-L121 |
convert int to string | python | def num2varint(num):
"""
Converts a number to a variable length Int. Used for array length header
:param: {number} num - The number
:return: {string} hexstring of the variable Int.
"""
# if (typeof num !== 'number') throw new Error('VarInt must be numeric')
# if (num < 0) throw new RangeError('VarInts are unsigned (> 0)')
# if (!Number.isSafeInteger(num)) throw new RangeError('VarInt must be a safe integer')
if num < 0xfd:
return num2hexstring(num)
elif num <= 0xffff:
# uint16
return 'fd' + num2hexstring(number=num, size=2, little_endian=True)
elif num <= 0xffffffff:
# uint32
return 'fe' + num2hexstring(number=num, size=4, little_endian=True)
else:
# uint64
return 'ff' + num2hexstring(number=num, size=8, little_endian=True) | https://github.com/KeithSSmith/switcheo-python/blob/22f943dea1ad7d692b2bfcd9f0822ec80f4641a6/switcheo/utils.py#L50-L70 |
convert int to string | python | def positive_int(string):
"""Convert string to positive integer."""
error_msg = 'Positive integer required, {string} given.'.format(string=string)
try:
value = int(string)
except ValueError:
raise ArgumentTypeError(error_msg)
if value < 0:
raise ArgumentTypeError(error_msg)
return value | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/util/__init__.py#L64-L73 |
convert int to string | python | def _convert_to_float_if_possible(s):
"""
A small helper function to convert a string to a numeric value
if appropriate
:param s: the string to be converted
:type s: str
"""
try:
ret = float(s)
except (ValueError, TypeError):
ret = s
return ret | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/operators/check_operator.py#L98-L110 |
convert int to string | python | def to_string(s, encoding=None, errors='strict'):
"""Inverse of to_bytes"""
if isinstance(s, bytes):
return s.decode(encoding or 'utf-8', errors)
elif not isinstance(s, str):
return str(s)
else:
return s | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/string.py#L21-L28 |
convert int to string | python | def get_int(self):
"""
Fetch an int from the stream.
:return: a 32-bit unsigned `int`.
"""
byte = self.get_bytes(1)
if byte == max_byte:
return util.inflate_long(self.get_binary())
byte += self.get_bytes(3)
return struct.unpack('>I', byte)[0] | https://github.com/NikolayDachev/jadm/blob/12bb550445edfcd87506f7cba7a6a35d413c5511/lib/paramiko-1.14.1/paramiko/message.py#L132-L142 |
convert int to string | python | def convert_to_int(value, from_base):
"""
Convert value to an int.
:param value: the value to convert
:type value: sequence of int
:param int from_base: base of value
:returns: the conversion result
:rtype: int
:raises ConvertError: if from_base is less than 2
:raises ConvertError: if elements in value outside bounds
Preconditions:
* all integers in value must be at least 0
* all integers in value must be less than from_base
* from_base must be at least 2
Complexity: O(len(value))
"""
if from_base < 2:
raise BasesValueError(
from_base,
"from_base",
"must be greater than 2"
)
if any(x < 0 or x >= from_base for x in value):
raise BasesValueError(
value,
"value",
"elements must be at least 0 and less than %s" % from_base
)
return reduce(lambda x, y: x * from_base + y, value, 0) | https://github.com/mulkieran/justbases/blob/dd52ff4b3d11609f54b2673599ee4eeb20f9734f/src/justbases/_nats.py#L59-L91 |
convert int to string | python | def normalize_int(value: IntConvertible) -> int:
"""
Robust to integer conversion, handling hex values, string representations,
and special cases like `0x`.
"""
if is_integer(value):
return cast(int, value)
elif is_bytes(value):
return big_endian_to_int(value)
elif is_hex(value) and is_0x_prefixed(value):
value = cast(str, value)
if len(value) == 2:
return 0
else:
return int(value, 16)
elif is_string(value):
return int(value)
else:
raise TypeError("Unsupported type: Got `{0}`".format(type(value))) | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/_utils/normalization.py#L72-L90 |
convert int to string | python | def convert_bytes_to_ints(in_bytes, num):
"""Convert a byte array into an integer array. The number of bytes forming an integer
is defined by num
:param in_bytes: the input bytes
:param num: the number of bytes per int
:return the integer array"""
out_arr = []
for i in range(len(in_bytes)//num):
val = in_bytes[i * num:i * num + num]
unpacked = struct.unpack(mmtf.utils.constants.NUM_DICT[num], val)
out_arr.append(unpacked[0])
return out_arr | https://github.com/rcsb/mmtf-python/blob/899bb877ca1b32a9396803d38c5bf38a2520754e/mmtf/converters/converters.py#L9-L20 |
convert int to string | python | def to_int(value, default=_marker):
"""Tries to convert the value to int.
Truncates at the decimal point if the value is a float
:param value: The value to be converted to an int
:return: The resulting int or default
"""
if is_floatable(value):
value = to_float(value)
try:
return int(value)
except (TypeError, ValueError):
if default is None:
return default
if default is not _marker:
return to_int(default)
fail("Value %s cannot be converted to int" % repr(value)) | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/api/__init__.py#L1257-L1273 |
convert int to string | python | def _toIntList(numstr, acceptX=0):
"""
Convert ans string to a list removing all invalid characters.
Receive: a string as a number
"""
res = []
# Converting and removing invalid characters
for i in numstr:
if i in string.digits and i not in string.letters:
res.append(int(i))
# Converting control number into ISBN
if acceptX and (numstr[-1] in 'Xx'):
res.append(10)
return res | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/validators.py#L1046-L1060 |
convert int to string | python | def cast_int(x):
"""
Cast unknown type into integer
:param any x:
:return int:
"""
try:
x = int(x)
except ValueError:
try:
x = x.strip()
except AttributeError as e:
logger_misc.warn("parse_str: AttributeError: String not number or word, {}, {}".format(x, e))
return x | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/misc.py#L60-L74 |
convert int to string | python | def _int_from_str(string):
"""
Convert string into integer
Raise:
TypeError if string is not a valid integer
"""
float_num = float(string)
int_num = int(float_num)
if float_num == int_num:
return int_num
else:
# Needed to handle pseudos with fractional charge
int_num = np.rint(float_num)
logger.warning("Converting float %s to int %s" % (float_num, int_num))
return int_num | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/pseudos.py#L632-L647 |
convert int to string | python | def type_converter(text):
""" I convert strings into integers, floats, and strings! """
if text.isdigit():
return int(text), int
try:
return float(text), float
except ValueError:
return text, STRING_TYPE | https://github.com/pydanny/simplicity/blob/aef4ce39b0965b8d333c67c9d6ec5baecee9c617/simplicity.py#L95-L103 |
convert int to string | python | def int_bytes(cls, string):
'''Convert string describing size to int.'''
if string[-1] in ('k', 'm'):
value = cls.int_0_inf(string[:-1])
unit = string[-1]
if unit == 'k':
value *= 2 ** 10
else:
value *= 2 ** 20
return value
else:
return cls.int_0_inf(string) | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/options.py#L123-L134 |
convert int to string | python | def text_to_int(text, default_base="hex"):
""" Convert text to int, raising exeception on invalid input
"""
if text.startswith("0x"):
value = int(text[2:], 16)
elif text.startswith("$"):
value = int(text[1:], 16)
elif text.startswith("#"):
value = int(text[1:], 10)
elif text.startswith("%"):
value = int(text[1:], 2)
else:
if default_base == "dec":
value = int(text)
else:
value = int(text, 16)
return value | https://github.com/robmcmullen/atrcopy/blob/dafba8e74c718e95cf81fd72c184fa193ecec730/atrcopy/utils.py#L44-L60 |
convert int to string | python | def long2str(l):
"""Convert an integer to a string."""
if type(l) not in (types.IntType, types.LongType):
raise ValueError('the input must be an integer')
if l < 0:
raise ValueError('the input must be greater than 0')
s = ''
while l:
s = s + chr(l & 255)
l >>= 8
return s | https://github.com/zeaphoo/reston/blob/96502487b2259572df55237c9526f92627465088/reston/core/anconf.py#L152-L164 |
convert int to string | python | def convert(self, value, param, ctx):
""" Convert value to int. """
self.gandi = ctx.obj
value = click.Choice.convert(self, value, param, ctx)
return int(value) | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/params.py#L198-L202 |
convert int to string | python | def _int(int_or_str: Any) -> int:
"return an integer where a single character string may be expected"
if isinstance(int_or_str, str):
return ord(int_or_str)
if isinstance(int_or_str, bytes):
return int_or_str[0]
return int(int_or_str) | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/tcod.py#L15-L21 |
convert int to string | python | def str2int(self, str_value):
"""Conversion class name string => integer."""
str_value = tf.compat.as_text(str_value)
if self._str2int:
return self._str2int[str_value]
# No names provided, try to integerize
failed_parse = False
try:
int_value = int(str_value)
except ValueError:
failed_parse = True
if failed_parse or not 0 <= int_value < self._num_classes:
raise ValueError("Invalid string class label %s" % str_value)
return int_value | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/class_label_feature.py#L99-L113 |
convert int to string | python | def decode_int(self, str):
""" Decodes a short Base64 string into an integer.
Example:
``decode_int('B7')`` returns ``123``.
"""
n = 0
for c in str:
n = n * self.BASE + self.ALPHABET_REVERSE[c]
return n | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/token_manager.py#L216-L225 |
convert int to string | python | def convert_string_to_number(value):
"""
Convert strings to numbers
"""
if value is None:
return 1
if isinstance(value, int):
return value
if value.isdigit():
return int(value)
num_list = map(lambda s: NUMBERS[s], re.findall(numbers + '+', value.lower()))
return sum(num_list) | https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/parsing.py#L506-L517 |
convert int to string | python | def _revint(self, version):
'''
Internal function to convert a version string to an integer.
'''
intrev = 0
vsplit = version.split('.')
for c in range(len(vsplit)):
item = int(vsplit[c]) * (10 ** (((len(vsplit) - c - 1) * 2)))
intrev += item
return intrev | https://github.com/SteveMcGrath/pySecurityCenter/blob/f0b10b1bcd4fd23a8d4d09ca6774cdf5e1cfd880/securitycenter/sc4.py#L41-L50 |
convert int to string | python | def int_or_str(v: Optional[str]) -> Union[None, int, str]:
"""Safe converts an string represent an integer to an integer or passes through ``None``."""
if v is None:
return
try:
return int(v)
except ValueError:
return v | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/utils.py#L59-L66 |
convert int to string | python | def convert_ints_to_bytes(in_ints, num):
"""Convert an integer array into a byte arrays. The number of bytes forming an integer
is defined by num
:param in_ints: the input integers
:param num: the number of bytes per int
:return the integer array"""
out_bytes= b""
for val in in_ints:
out_bytes+=struct.pack(mmtf.utils.constants.NUM_DICT[num], val)
return out_bytes | https://github.com/rcsb/mmtf-python/blob/899bb877ca1b32a9396803d38c5bf38a2520754e/mmtf/converters/converters.py#L22-L32 |
convert int to string | python | def intToBin(i):
""" Integer to two bytes """
# devide in two parts (bytes)
i1 = i % 256
i2 = int(i / 256)
# make string (little endian)
return chr(i1) + chr(i2) | https://github.com/thumbor/thumbor/blob/558ccdd6e3bc29e1c9ee3687372c4b3eb05ac607/thumbor/engines/extensions/pil.py#L132-L138 |
convert int to string | python | def to_int(argument):
"""
Converts the ``str`` argument to an integer:
>>> from py_register_machine2.engine_tools.conversions import *
>>> to_int("0x04")
4
>>> to_int("'a'")
97
"""
if(argument.startswith("0b")):
return int(argument[2:], 2)
elif(argument.startswith("0x")):
return int(argument[2:], 16)
elif(argument.startswith("0") and argument != "0"):
return int(argument[1:], 8)
elif(argument[0] == "'" and argument[2] == "'"):
return ord(argument[1])
return int(argument) | https://github.com/daknuett/py_register_machine2/blob/599c53cd7576297d0d7a53344ed5d9aa98acc751/engine_tools/conversions.py#L56-L75 |
convert int to string | python | def convert_string(string, chars=None):
"""Remove certain characters from a string."""
if chars is None:
chars = [',', '.', '-', '/', ':', ' ']
for ch in chars:
if ch in string:
string = string.replace(ch, ' ')
return string | https://github.com/sharibarboza/py_zap/blob/ce90853efcad66d3e28b8f1ac910f275349d016c/py_zap/utils.py#L34-L42 |
convert int to string | python | def rbigint_to_string(obj):
""" Recursively converts big integers (|>2**53-1|) to strings
@obj: Any python object
-> @obj, with any big integers converted to #str objects
"""
if isinstance(obj, (str, bytes)) or not obj:
# the input is the desired one, return as is
return obj
elif hasattr(obj, 'items'):
# the input is a dict {}
for k, item in obj.items():
obj[k] = rbigint_to_string(item)
return obj
elif hasattr(obj, '__iter__'):
# the input is iterable
is_tuple = isinstance(obj, tuple)
if is_tuple:
obj = list(obj)
for i, item in enumerate(obj):
obj[i] = rbigint_to_string(item)
return obj if not is_tuple else tuple(obj)
return bigint_to_string(obj) | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/tools/strings.py#L104-L127 |
convert int to string | python | def _string_to_int(self, s):
"""Read an integer in s, in Little Indian. """
base = len(self.alphabet)
return sum((self._letter_to_int(l) * base**lsb
for lsb, l in enumerate(s)
)) | https://github.com/Aluriak/ACCC/blob/9092f985bef7ed784264c86bc19c980f4ce2309f/accc/compiler/compiler.py#L196-L201 |
convert int to string | python | def str_to_num(i, exact_match=True):
"""
Attempts to convert a str to either an int or float
"""
# TODO: Cleanup -- this is really ugly
if not isinstance(i, str):
return i
try:
if not exact_match:
return int(i)
elif str(int(i)) == i:
return int(i)
elif str(float(i)) == i:
return float(i)
else:
pass
except ValueError:
pass
return i | https://github.com/rtluckie/seria/blob/8ae4f71237e69085d8f974a024720f45b34ab963/seria/utils.py#L3-L21 |
convert int to string | python | def decode_int(tag, bits_per_char=6):
"""Decode string into int assuming encoding with `encode_int()`
It is using 2, 4 or 6 bits per coding character (default 6).
Parameters:
tag: str Encoded integer.
bits_per_char: int The number of bits per coding character.
Returns:
int: the decoded string
"""
if bits_per_char == 6:
return _decode_int64(tag)
if bits_per_char == 4:
return _decode_int16(tag)
if bits_per_char == 2:
return _decode_int4(tag)
raise ValueError('`bits_per_char` must be in {6, 4, 2}') | https://github.com/tammoippen/geohash-hilbert/blob/b74f0fc1bff0234d8ff367e4129c3324676b0b36/geohash_hilbert/_int2str.py#L52-L71 |
convert int to string | python | def parse_int(int_str):
"""Parse a string of the form 1,234,567b into a Python integer.
The terminal letter, if present, indicates e.g. billions."""
int_str = int_str.replace(',', '')
factor = __get_factor(int_str)
if factor != 1:
int_str = int_str[:-1]
try:
return int(int_str.replace(',', '')) * factor
except ValueError:
return None | https://github.com/StefanKopieczek/ticker/blob/6dcc1bf8f55bf8612986833097531ecf021b687c/ticker/ticker_parsers.py#L4-L16 |
convert int to string | python | def _to_bytes(value, encoding="ascii"):
"""Converts a string value to bytes, if necessary.
Unfortunately, ``six.b`` is insufficient for this task since in
Python2 it does not modify ``unicode`` objects.
:type value: str / bytes or unicode
:param value: The string/bytes value to be converted.
:type encoding: str
:param encoding: The encoding to use to convert unicode to bytes. Defaults
to "ascii", which will not allow any characters from
ordinals larger than 127. Other useful values are
"latin-1", which which will only allows byte ordinals
(up to 255) and "utf-8", which will encode any unicode
that needs to be.
:rtype: str / bytes
:returns: The original value converted to bytes (if unicode) or as passed
in if it started out as bytes.
:raises TypeError: if the value could not be converted to bytes.
"""
result = value.encode(encoding) if isinstance(value, six.text_type) else value
if isinstance(result, six.binary_type):
return result
else:
raise TypeError("%r could not be converted to bytes" % (value,)) | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/core/google/cloud/_helpers.py#L344-L370 |
convert int to string | python | def ip_to_int(ip):
'''
Converts an IP address to an integer
'''
ret = 0
for octet in ip.split('.'):
ret = ret * 256 + int(octet)
return ret | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/cloud.py#L2415-L2422 |
convert int to string | python | def _ipv4_text_to_int(self, ip_text):
"""convert ip v4 string to integer."""
if ip_text is None:
return None
assert isinstance(ip_text, str)
return struct.unpack('!I', addrconv.ipv4.text_to_bin(ip_text))[0] | https://github.com/osrg/ryu/blob/6f906e72c92e10bd0264c9b91a2f7bb85b97780c/ryu/lib/igmplib.py#L237-L242 |
convert int to string | python | def convert_to_int(x: Any, default: int = None) -> int:
"""
Transforms its input into an integer, or returns ``default``.
"""
try:
return int(x)
except (TypeError, ValueError):
return default | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/convert.py#L76-L83 |