query
stringlengths
9
60
language
stringclasses
1 value
code
stringlengths
105
25.7k
url
stringlengths
91
217
convert string to number
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 string to number
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 string to number
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 string to number
python
def _number(text): ''' Convert a string to a number. Returns an integer if the string represents an integer, a floating point number if the string is a real number, or the string unchanged otherwise. ''' if text.isdigit(): return int(text) try: return float(text) except ValueError: return text
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L59-L71
convert string to number
python
def to_number(s): """ Convert a string to a number. If not successful, return the string without blanks """ ret = s # try converting to float try: ret = float(s) except ValueError: ret = ret.strip('\'').strip() # try converting to uid try: ret = int(s) except ValueError: pass # try converting to boolean if ret == 'True': ret = True elif ret == 'False': ret = False elif ret == 'None': ret = None return ret
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/utils/math.py#L134-L159
convert string to number
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 string to number
python
def toNumber (str, default=None): """toNumber(str[, default]) -> integer | float | default Converts the given string to a numeric value. The string may be a hexadecimal, integer, or floating number. If string could not be converted, default (None) is returned. Examples: >>> n = toNumber("0x2A") >>> assert type(n) is int and n == 42 >>> n = toNumber("42") >>> assert type(n) is int and n == 42 >>> n = toNumber("42.0") >>> assert type(n) is float and n == 42.0 >>> n = toNumber("Foo", 42) >>> assert type(n) is int and n == 42 >>> n = toNumber("Foo") >>> assert n is None """ value = default try: if str.startswith("0x"): value = int(str, 16) else: try: value = int(str) except ValueError: value = float(str) except ValueError: pass return value
https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/util.py#L305-L342
convert string to number
python
def cast_to_number_or_bool(inputstr): """Cast a string to int, float or bool. Return original string if it can't be converted. Scientific expression is converted into float. """ if inputstr.strip().lower() == "true": return True elif inputstr.strip().lower() == "false": return False try: return int(inputstr) except ValueError: try: return float(inputstr) except ValueError: return inputstr
https://github.com/googlefonts/glyphsLib/blob/9c12dc70c8d13f08d92b824e6710f6e3bb5037bb/Lib/glyphsLib/util.py#L68-L84
convert string to number
python
def _convert_number(self, number): """Converts a number to float or int as appropriate""" number = float(number) return int(number) if number.is_integer() else float(number)
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/api.py#L46-L50
convert string to number
python
def number(input): """Convert the given input to a floating point or integer value. In cases of ambiguity, integers will be prefered to floating point. :param input: the value to convert to a number :type input: any :returns: converted integer value :rtype: float or int """ try: return int(input) except (TypeError, ValueError): pass try: return float(input) except (TypeError, ValueError): raise ValueError("Unable to convert {0!r} to a number.".format(input))
https://github.com/marrow/util/blob/abb8163dbd1fa0692d42a44d129b12ae2b39cdf2/marrow/util/convert.py#L137-L157
convert string to number
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 string to number
python
def __convert_num(number): """ All path items are automatically strings. If you think it's an int or float, this attempts to convert it. :param str number: :return float or str: """ try: return float(number) except ValueError as e: logger_noaa_lpd.warn("convert_num: ValueError: {}".format(e)) return number
https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/noaa_lpd.py#L546-L556
convert string to number
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 string to number
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 string to number
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 string to number
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 string to number
python
def format_number(x): """Format number to string Function converts a number to string. For numbers of class :class:`float`, up to 17 digits will be used to print the entire floating point number. Any padding zeros will be removed at the end of the number. See :ref:`user-guide:int` and :ref:`user-guide:double` for more information on the format. .. note:: IEEE754-1985 standard says that 17 significant decimal digits are required to adequately represent a 64-bit floating point number. Not all fractional numbers can be exactly represented in floating point. An example is 0.1 which will be approximated as 0.10000000000000001. Parameters ---------- x : :class:`int` or :class:`float` Number to convert to string Returns ------- vector : :class:`str` String of number :obj:`x` """ if isinstance(x, float): # Helps prevent loss of precision as using str() in Python 2 only prints 12 digits of precision. # However, IEEE754-1985 standard says that 17 significant decimal digits is required to adequately represent a # floating point number. # The g option is used rather than f because g precision uses significant digits while f is just the number of # digits after the decimal. (NRRD C implementation uses g). value = '{:.17g}'.format(x) else: value = str(x) return value
https://github.com/mhe/pynrrd/blob/96dd875b302031ea27e2d3aaa611dc6f2dfc7979/nrrd/formatters.py#L4-L38
convert string to number
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 string to number
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 string to number
python
def to_decimal(number, strip='- '): ''' Converts a number to a string of decimals in base 10. >>> to_decimal(123) '123' >>> to_decimal('o123') '83' >>> to_decimal('b101010') '42' >>> to_decimal('0x2a') '42' ''' if isinstance(number, six.integer_types): return str(number) number = str(number) number = re.sub(r'[%s]' % re.escape(strip), '', number) # hexadecimal if number.startswith('0x'): return to_decimal(int(number[2:], 16)) # octal elif number.startswith('o'): return to_decimal(int(number[1:], 8)) # binary elif number.startswith('b'): return to_decimal(int(number[1:], 2)) else: return str(int(number))
https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/util.py#L71-L103
convert string to number
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 string to number
python
def dec2str(n): """ decimal number to string. """ s = hex(int(n))[2:].rstrip('L') if len(s) % 2 != 0: s = '0' + s return hex2str(s)
https://github.com/restran/mountains/blob/a97fee568b112f4e10d878f815d0db3dd0a98d74/mountains/encoding/converter.py#L163-L170
convert string to number
python
def numberize(string): '''Turns a string into a number (``int`` or ``float``) if it's only a number (ignoring spaces), otherwise returns the string. For example, ``"5 "`` becomes ``5`` and ``"2 ton"`` remains ``"2 ton"``''' if not isinstance(string,basestring): return string just_int = r'^\s*[-+]?\d+\s*$' just_float = r'^\s*[-+]?\d+\.(\d+)?\s*$' if re.match(just_int,string): return int(string) if re.match(just_float,string): return float(string) return string
https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/utils.py#L432-L443
convert string to number
python
def num_or_str(x): """The argument is a string; convert to a number if possible, or strip it. >>> num_or_str('42') 42 >>> num_or_str(' 42x ') '42x' """ if isnumber(x): return x try: return int(x) except ValueError: try: return float(x) except ValueError: return str(x).strip()
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/utils.py#L521-L535
convert string to number
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 string to number
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 string to number
python
def bytes_to_number(b, endian='big'): """ Convert a string to an integer. :param b: String or bytearray to convert. :param endian: Byte order to convert into ('big' or 'little' endian-ness, default 'big') Assumes bytes are 8 bits. This is a special-case version of string_to_number with a full base-256 ASCII alphabet. It is the reverse of ``number_to_bytes(n)``. Examples:: >>> bytes_to_number(b'*') 42 >>> bytes_to_number(b'\\xff') 255 >>> bytes_to_number(b'\\x01\\x00') 256 >>> bytes_to_number(b'\\x00\\x01', endian='little') 256 """ if endian == 'big': b = reversed(b) n = 0 for i, ch in enumerate(bytearray(b)): n ^= ch << i * 8 return n
https://github.com/shazow/unstdlib.py/blob/e0632fe165cfbfdb5a7e4bc7b412c9d6f2ebad83/unstdlib/standard/string_.py#L115-L149
convert string to number
python
def tovalue(self, fmt='Q'): ''' Convert bitstring to a int/long number. ''' format_size = struct.calcsize(fmt) if self.length() > format_size * 8: raise TypeError('Cannot convert to number') ba = self.copy() ba.extend((format_size * 8 - self.length()) * [0]) return struct.unpack_from(fmt, ba.tobytes())[0]
https://github.com/SiLab-Bonn/basil/blob/99052482d9334dd1f5598eb2d2fb4d5399a32291/basil/utils/BitLogic.py#L57-L66
convert string to number
python
def _num_to_string(self, number, pad_to_length=None): """ Convert a number to a string, using the given alphabet. """ output = "" while number: number, digit = divmod(number, self._alpha_len) output += self._alphabet[digit] if pad_to_length: remainder = max(pad_to_length - len(output), 0) output = output + self._alphabet[0] * remainder return output
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/extern/shortuuid/__init__.py#L17-L28
convert string to number
python
def to_number(result_type, value, default=None, minimum=None, maximum=None): """Cast `value` to numeric `result_type` if possible Args: result_type (type): Numerical type to convert to (one of: int, float, ...) value (str | unicode): Value to convert default (result_type.__class__ | None): Default to use `value` can't be turned into an int minimum (result_type.__class__ | None): If specified, result can't be below this minimum maximum (result_type.__class__ | None): If specified, result can't be above this maximum Returns: Corresponding numeric value """ try: return capped(result_type(value), minimum, maximum) except (TypeError, ValueError): return default
https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/config.py#L451-L468
convert string to number
python
def _isnumber(string): """ >>> _isnumber("123.45") True >>> _isnumber("123") True >>> _isnumber("spam") False >>> _isnumber("123e45678") False >>> _isnumber("inf") True """ if not _isconvertible(float, string): return False elif isinstance(string, (_text_type, _binary_type)) and ( math.isinf(float(string)) or math.isnan(float(string))): return string.lower() in ['inf', '-inf', 'nan'] return True
https://github.com/raphaelvallat/pingouin/blob/58b19fa4fffbfe09d58b456e3926a148249e4d9b/pingouin/external/tabulate.py#L429-L447
convert string to number
python
def number(v): """Convert a value to a number.""" if nodesetp(v): v = string(v) try: return float(v) except ValueError: return float('NaN')
https://github.com/gabrielfalcao/dominic/blob/a42f418fc288f3b70cb95847b405eaf7b83bb3a0/dominic/xpath/expr.py#L133-L140
convert string to number
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 string to number
python
def get_number(s, cast=int): """ Try to get a number out of a string, and cast it. """ import string d = "".join(x for x in str(s) if x in string.digits) return cast(d)
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/base.py#L495-L501
convert string to number
python
def toFloat (str, default=None): """toFloat(str[, default]) -> float | default Converts the given string to a floating-point value. If the string could not be converted, default (None) is returned. NOTE: This method is *significantly* more effecient than toNumber() as it only attempts to parse floating-point numbers, not integers or hexadecimal numbers. Examples: >>> f = toFloat("4.2") >>> assert type(f) is float and f == 4.2 >>> f = toFloat("UNDEFINED", 999.9) >>> assert type(f) is float and f == 999.9 >>> f = toFloat("Foo") >>> assert f is None """ value = default try: value = float(str) except ValueError: pass return value
https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/util.py#L274-L302
convert string to number
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 string to number
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 string to number
python
def string_to_general_float(s: str) -> float: """ Convert a string to corresponding single or double precision scientific number. :param s: a string could be '0.1', '1e-5', '1.0D-5', or any other validated number :return: a float or raise an error .. doctest:: >>> string_to_general_float('1.0D-5') 1e-05 >>> string_to_general_float('1Dx') Traceback (most recent call last): ... ValueError: The string '1Dx' does not corresponds to a double precision number! >>> string_to_general_float('.8d234') 8e+233 >>> string_to_general_float('0.1') 0.1 """ if 'D' in s.upper(): # Possible double precision number try: return string_to_double_precision_float(s) except ValueError: raise ValueError( "The string '{0}' does not corresponds to a double precision number!".format(s)) else: return float(s)
https://github.com/singularitti/scientific-string/blob/615dca747e8fb1e89ed1d9f18aef4066295a17a9/scientific_string/strings.py#L93-L120
convert string to number
python
def _convert_number_to_subscript(num): """ Converts number into subscript input = ["a", "a1", "a2", "a3", "be2", "be3", "bad2", "bad3"] output = ["a", "a₁", "a₂", "a₃", "be₂", "be₃", "bad₂", "bad₃"] :param num: number called after sign :return: number in subscript """ subscript = '' for character in str(num): subscript += chr(0x2080 + int(character)) return subscript
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/stem/akkadian/atf_converter.py#L66-L79
convert string to number
python
def convert_id36_to_numeric_id(id36): """Convert strings representing base36 numbers into an integer.""" if not isinstance(id36, six.string_types) or id36.count("_") > 0: raise ValueError("must supply base36 string, not fullname (e.g. use " "xxxxx, not t3_xxxxx)") return int(id36, 36)
https://github.com/michael-lazar/rtv/blob/ccef2af042566ad384977028cf0bde01bc524dda/rtv/packages/praw/helpers.py#L382-L387
convert string to number
python
def format_number(number, format): """Format `number` according the given `format` (:class:`NumberFormat`)""" if format == NumberFormat.NUMBER: return str(number) elif format == NumberFormat.LOWERCASE_CHARACTER: string = '' while number > 0: number, ordinal = divmod(number, 26) if ordinal == 0: ordinal = 26 number -= 1 string = chr(ord('a') - 1 + ordinal) + string return string elif format == NumberFormat.UPPERCASE_CHARACTER: return format_number(number, 'lowercase character').upper() elif format == NumberFormat.LOWERCASE_ROMAN: return romanize(number).lower() elif format == NumberFormat.UPPERCASE_ROMAN: return romanize(number) elif format == NumberFormat.SYMBOL: return symbolize(number) elif format == NumberFormat.NONE: return '' else: raise ValueError("Unknown number format '{}'".format(format))
https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/number.py#L37-L61
convert string to number
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 string to number
python
def isNumber(s): """ Determines if a unicode string (that may include commas) is a number. :param s: Any unicode string. :return: True if s represents a number, False otherwise. """ s = s.replace(',', '') try: float(s) return True except ValueError: pass try: import unicodedata unicodedata.numeric(s) return True except (TypeError, ValueError) as e: pass return False
https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/lib/ec2nodes.py#L78-L97
convert string to number
python
def is_number(string): """ checks if a string is a number (int/float) """ string = str(string) if string.isnumeric(): return True try: float(string) return True except ValueError: return False
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/tools.py#L89-L98
convert string to number
python
def number_to_bytes(n, endian='big'): """ Convert an integer to a corresponding string of bytes.. :param n: Integer to convert. :param endian: Byte order to convert into ('big' or 'little' endian-ness, default 'big') Assumes bytes are 8 bits. This is a special-case version of number_to_string with a full base-256 ASCII alphabet. It is the reverse of ``bytes_to_number(b)``. Examples:: >>> r(number_to_bytes(42)) b'*' >>> r(number_to_bytes(255)) b'\\xff' >>> r(number_to_bytes(256)) b'\\x01\\x00' >>> r(number_to_bytes(256, endian='little')) b'\\x00\\x01' """ res = [] while n: n, ch = divmod(n, 256) if PY3: res.append(ch) else: res.append(chr(ch)) if endian == 'big': res.reverse() if PY3: return bytes(res) else: return ''.join(res)
https://github.com/shazow/unstdlib.py/blob/e0632fe165cfbfdb5a7e4bc7b412c9d6f2ebad83/unstdlib/standard/string_.py#L152-L193
convert string to number
python
def _convert_num(self, sign): """ Converts number registered in get_number_from_sign. input = ["a2", "☉", "be3"] output = ["a₂", "☉", "be₃"] :param sign: string :return sign: string """ # Check if there's a number at the end new_sign, num = self._get_number_from_sign(sign) if num < 2: # "ab" -> "ab" return new_sign.replace(str(num), self._convert_number_to_subscript(num)) if num > 3: # "buru14" -> "buru₁₄" return new_sign.replace(str(num), self._convert_number_to_subscript(num)) if self.two_three: # pylint: disable=no-else-return return new_sign.replace(str(num), self._convert_number_to_subscript(num)) else: # "bad3" -> "bàd" for i, character in enumerate(new_sign): new_vowel = '' if character in VOWELS: if num == 2: # noinspection PyUnusedLocal new_vowel = character + chr(0x0301) elif num == 3: new_vowel = character + chr(0x0300) break return new_sign[:i] + normalize('NFC', new_vowel) + \ new_sign[i+1:].replace(str(num), '')
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/stem/akkadian/atf_converter.py#L100-L133
convert string to number
python
def _cast_number(value): # source: https://bitbucket.org/openpyxl/openpyxl/src/93604327bce7aac5e8270674579af76d390e09c0/openpyxl/cell/read_only.py?at=default&fileviewer=file-view-default "Convert numbers as string to an int or float" m = FLOAT_REGEX.search(value) if m is not None: return float(value) return int(value)
https://github.com/anthill/koala/blob/393089fe081380506e73235db18a32b4e078d222/koala/reader.py#L74-L79
convert string to number
python
def convert_value(self, value): """Convert string 93,000.00 to float 93000.0.""" if isinstance(value, str): value = value.replace(self.separator, '') if self.decimal_point not in value: return int(value) else: return float(value.replace(self.decimal_point, '.')) elif self.int_to_float: return float(value) else: return value
https://github.com/data-8/datascience/blob/4cee38266903ca169cea4a53b8cc39502d85c464/datascience/formats.py#L95-L106
convert string to number
python
def string_to_number(s, alphabet): """ Given a string ``s``, convert it to an integer composed of the given ``alphabet`` mapping, where the position of each element in ``alphabet`` is its radix value. Examples:: >>> string_to_number('101111000110000101001110', '01') 12345678 >>> string_to_number('babbbbaaabbaaaababaabbba', 'ab') 12345678 >>> string_to_number('ZXP0', string.ascii_letters + string.digits) 12345678 """ base = len(alphabet) inverse_alphabet = dict(zip(alphabet, xrange(0, base))) n = 0 exp = 0 for i in reversed(s): n += inverse_alphabet[i] * (base ** exp) exp += 1 return n
https://github.com/shazow/unstdlib.py/blob/e0632fe165cfbfdb5a7e4bc7b412c9d6f2ebad83/unstdlib/standard/string_.py#L86-L112
convert string to number
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 string to number
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 string to number
python
def number_to_string(n, alphabet): """ Given an non-negative integer ``n``, convert it to a string composed of the given ``alphabet`` mapping, where the position of each element in ``alphabet`` is its radix value. Examples:: >>> number_to_string(12345678, '01') '101111000110000101001110' >>> number_to_string(12345678, 'ab') 'babbbbaaabbaaaababaabbba' >>> number_to_string(12345678, string.ascii_letters + string.digits) 'ZXP0' >>> number_to_string(12345, ['zero ', 'one ', 'two ', 'three ', 'four ', 'five ', 'six ', 'seven ', 'eight ', 'nine ']) 'one two three four five ' """ result = '' base = len(alphabet) current = int(n) if current < 0: raise ValueError("invalid n (must be non-negative): %s", n) while current: result = alphabet[current % base] + result current = current // base return result
https://github.com/shazow/unstdlib.py/blob/e0632fe165cfbfdb5a7e4bc7b412c9d6f2ebad83/unstdlib/standard/string_.py#L53-L83
convert string to number
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 string to number
python
def _to_numeric_float(number, nums_int): """ Transforms a string into a float. The nums_int parameter indicates the number of characters, starting from the left, to be used for the integer value. All the remaining ones will be used for the decimal value. :param number: string with the number :param nums_int: characters, counting from the left, for the integer value :return: a float created from the string """ index_end = len(number) - nums_int return float(number[:nums_int] + '.' + number[-index_end:])
https://github.com/weso/CWR-DataApi/blob/f3b6ba8308c901b6ab87073c155c08e30692333c/cwr/grammar/field/basic.py#L245-L258
convert string to number
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 string to number
python
def decode_format(number_format): """ Convert style string to format string ('{}' style), suffix and value scale This is the core function used to convert numbers to strings """ style = number_format[0] prec = "." + str(int(number_format[1:])) if len(number_format) > 1 else "" if style == NUMBER: return "," + prec + "g","",1. elif style == THOUSANDS: return "," + prec + "g","k",1e-3 elif style == MILLIONS: return "," + prec + "g","m",1e-6 elif style == BILLIONS: return "," + prec + "g","bn",1e-9 elif style == TRILLIONS: return "," + prec + "g","tr",1e-12 elif style == PERCENTAGE: return prec + "f","%",1e2 elif style == BASIS_POINTS: return prec + "f","bp",1e4 elif style == INTEGER: return "d","",1. elif style == SCIENTIFIC: return ".4e","",1. else: # style FLOAT return prec + "f","",1.
https://github.com/ptav/django-simplecrud/blob/468f6322aab35c8001311ee7920114400a040f6c/simplecrud/format.py#L38-L76
convert string to number
python
def englishToPun_number(number): """This function converts the normal english number to the punjabi number with punjabi digits, its input will be an integer of type int, and output will be a string. """ output = '' number = list(str(number)) for digit in number: output += DIGITS[int(digit)] return output
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/punjabi/numerifier.py#L19-L28
convert string to number
python
def convertbase(number, base=10): """ Convert a number in base 10 to another base :type number: number :param number: The number to convert :type base: integer :param base: The base to convert to. """ integer = number if not integer: return '0' sign = 1 if integer > 0 else -1 alphanum = string.digits + string.ascii_lowercase nums = alphanum[:base] res = '' integer *= sign while integer: integer, mod = divmod(integer, base) res += nums[mod] return ('' if sign == 1 else '-') + res[::-1]
https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L1575-L1597
convert string to number
python
def itn(n, digits=8, format=DEFAULT_FORMAT): """Convert a python number to a number field. """ # POSIX 1003.1-1988 requires numbers to be encoded as a string of # octal digits followed by a null-byte, this allows values up to # (8**(digits-1))-1. GNU tar allows storing numbers greater than # that if necessary. A leading 0o200 byte indicates this particular # encoding, the following digits-1 bytes are a big-endian # representation. This allows values up to (256**(digits-1))-1. if 0 <= n < 8 ** (digits - 1): s = ("%0*o" % (digits - 1, n)).encode("ascii") + NUL else: if format != GNU_FORMAT or n >= 256 ** (digits - 1): raise ValueError("overflow in number field") if n < 0: # XXX We mimic GNU tar's behaviour with negative numbers, # this could raise OverflowError. n = struct.unpack("L", struct.pack("l", n))[0] s = bytearray() for i in range(digits - 1): s.insert(0, n & 0o377) n >>= 8 s.insert(0, 0o200) return s
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L216-L241
convert string to number
python
def _float(self, string): """Convert string to float Take care of numbers in exponential format """ string = self._denoise(string) exp_match = re.match(r'^[-.\d]+x10-(\d)$', string) if exp_match: exp = int(exp_match.groups()[0]) fac = 10 ** -exp string = string.replace('x10-{}'.format(exp), '') else: fac = 1 return fac * float(string)
https://github.com/pytroll/satpy/blob/1f21d20ac686b745fb0da9b4030d139893e066dd/satpy/readers/goes_imager_nc.py#L1280-L1294
convert string to number
python
def _convert_py_number(value): """Convert a Python integer value into equivalent C object. Will attempt to use the smallest possible conversion, starting with int, then long then double. """ try: return c_uamqp.int_value(value) except OverflowError: pass try: return c_uamqp.long_value(value) except OverflowError: pass return c_uamqp.double_value(value)
https://github.com/Azure/azure-uamqp-python/blob/b67e4fcaf2e8a337636947523570239c10a58ae2/uamqp/utils.py#L51-L64
convert string to number
python
def unhumanize_number(number): """Return number without formatting. If something goes wrong in the conversion just return the passed number We catch AttributeError in case the number has no replace method which means it is not a string but already an int or float We catch ValueError if number is a sting but not parseable to a number like the 'no data' case @param number: """ try: number = number.replace(thousand_separator(), '') number = int(float(number)) except (AttributeError, ValueError): pass return number
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/utilities.py#L446-L463
convert string to number
python
def is_a_number(s): """ This takes an object and determines whether it's a number or a string representing a number. """ if _s.fun.is_iterable(s) and not type(s) == str: return False try: float(s) return 1 except: try: complex(s) return 2 except: try: complex(s.replace('(','').replace(')','').replace('i','j')) return 2 except: return False
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_functions.py#L190-L209
convert string to number
python
def as_percent(precision=2, **kwargs): """Convert number to percentage string. Parameters: ----------- :param v: numerical value to be converted :param precision: int decimal places to round to """ if not isinstance(precision, Integral): raise TypeError("Precision must be an integer.") return _surpress_formatting_errors( _format_numer(".{}%".format(precision)) )
https://github.com/HHammond/PrettyPandas/blob/99a814ffc3aa61f66eaf902afaa4b7802518d33a/prettypandas/formatters.py#L40-L54
convert string to number
python
def _to_base36(number): """ Convert a positive integer to a base36 string. Taken from Stack Overflow and modified. """ if number < 0: raise ValueError("Cannot encode negative numbers") chars = "" while number != 0: number, i = divmod(number, 36) # 36-character alphabet chars = _alphabet[i] + chars return chars or "0"
https://github.com/abnerjacobsen/tinydb-jsonorm/blob/704d3f887cc8963769ffbb116eb7e6909deeaecd/src/tinydb_jsonorm/cuid.py#L20-L34
convert string to number
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 string to number
python
def integer(token): """ Convert numeric strings into integers. @type token: str @param token: String to parse. @rtype: int @return: Parsed integer value. """ token = token.strip() neg = False if token.startswith(compat.b('-')): token = token[1:] neg = True if token.startswith(compat.b('0x')): result = int(token, 16) # hexadecimal elif token.startswith(compat.b('0b')): result = int(token[2:], 2) # binary elif token.startswith(compat.b('0o')): result = int(token, 8) # octal else: try: result = int(token) # decimal except ValueError: result = int(token, 16) # hexadecimal (no "0x" prefix) if neg: result = -result return result
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/textio.py#L77-L105
convert string to number
python
def number_to_string(number, significant_digits, number_format_notation="f"): """ Convert numbers to string considering significant digits. """ try: using = number_formatting[number_format_notation] except KeyError: raise ValueError("number_format_notation got invalid value of {}. The valid values are 'f' and 'e'".format(number_format_notation)) from None if isinstance(number, Decimal): tup = number.as_tuple() with localcontext() as ctx: ctx.prec = len(tup.digits) + tup.exponent + significant_digits number = number.quantize(Decimal('0.' + '0' * significant_digits)) result = (using % significant_digits).format(number) # Special case for 0: "-0.00" should compare equal to "0.00" if set(result) <= ZERO_DECIMAL_CHARACTERS: result = "0.00" # https://bugs.python.org/issue36622 if number_format_notation == 'e' and isinstance(number, float): result = result.replace('+0', '+') return result
https://github.com/seperman/deepdiff/blob/a66879190fadc671632f154c1fcb82f5c3cef800/deepdiff/helper.py#L227-L247
convert string to number
python
def str_to_num(str_value): """Convert str_value to an int or a float, depending on the numeric value represented by str_value. """ str_value = str(str_value) try: return int(str_value) except ValueError: return float(str_value)
https://github.com/bheinzerling/descriptors/blob/04fff864649fba9bd6a2d8f8b649cf30994e0e46/descriptors/handmade.py#L167-L176
convert string to number
python
def convert_to_str(l: Node) -> str: """ converts the non-negative number list into a string. """ result = "" while l: result += str(l.val) l = l.next return result
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/linkedlist/add_two_numbers.py#L66-L74
convert string to number
python
def clean_german_number(x): """Convert a string with a German number into a Decimal Parameters ---------- x : str, list, tuple, numpy.ndarray, pandas.DataFrame A string with a number with German formatting, or an array of these strings, e.g. list, ndarray, df. Returns ------- y : str, list, tuple, numpy.ndarray, pandas.DataFrame A string or array of strings that can be converted to a numeric data type (e.g. Decimal, float, int). Example ------- The function aims to convert a string as follows '1.234' => '1234' '1234' => '1234' '1.234,56' => '1234.56' '1.234.560' => '1234560' '+123' => '123' '-123' => '-123' Code Example ------------ print(clean_german_number('1.234,56')) '1234.56' Behavior -------- - The function will return None if the element is not a string - The function assumes that provided string are German numbers. - There will NO check if it is a regular number. - No conversion to a numeric data type (have to be done afterwards) Notes ----- The command `x.dropna().apply(proc_elem)` is not working for pandas dataframes. Maybe the `proc_elem` sub function is too big or complex for pandas' apply method. """ import numpy as np import pandas as pd import re def proc_elem(e): # abort if it is not a string if not isinstance(e, str): return None # strip all char except digits, ".", "," and "-" s = re.sub('[^0-9\.\,\-]+', '', e) # abort if nothing is left if len(s) is 0: return None # extra check regarding "-" modifier m = "" if s[0] is "-": if len(s) > 1: m = "-" s = s[1:] else: return None # remove the "-" from the string s = re.sub('[^0-9\.\,]+', '', s) # abort if nothing is left if len(s) is 0: return None # abort if the number of "," (decimal sep) is bigger than 1 if s.count(',') > 1: return None # about if the decimal sep "," occurs before a 000' sep "." if s.count('.') > 0 and s.count(',') > 0: rev = s[::-1] if rev.find(",") > rev.find("."): return None # remove 000' seperators "." s = s.replace('.', '') # convert comma to dot s = s.replace(',', '.') # if just a dot is left "." if s == ".": return None # reattach the "-" modifier return m + s def proc_list(x): return [proc_elem(e) for e in x] def proc_ndarray(x): tmp = proc_list(list(x.reshape((x.size,)))) return np.array(tmp).reshape(x.shape) # transform string, list/tuple, numpy array, pandas dataframe if isinstance(x, str): return proc_elem(x) elif isinstance(x, (list, tuple)): return proc_list(x) elif isinstance(x, np.ndarray): return proc_ndarray(x) elif isinstance(x, pd.DataFrame): return pd.DataFrame(proc_ndarray(x.values), columns=x.columns, index=x.index) else: return None
https://github.com/ulf1/oxyba/blob/b3043116050de275124365cb11e7df91fb40169d/oxyba/clean_german_number.py#L2-L121
convert string to number
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 string to number
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 string to number
python
def friendly_number(num): """ Convert a base 10 number to a base X string. Charcters from VALID_CHARS are chosen, to convert the number to eg base 24, if there are 24 characters to choose from. Use valid chars to choose characters that are friendly, avoiding ones that could be confused in print or over the phone. """ # Convert to a (shorter) string for human consumption string = "" # The length of the string can be determined by STRING_LENGTH or by how many # characters are necessary to present a base 30 representation of SIZE. while STRING_LENGTH and len(string) <= STRING_LENGTH \ or len(VALID_CHARS) ** len(string) <= SIZE: # PREpend string (to remove all obvious signs of order) string = VALID_CHARS[num % len(VALID_CHARS)] + string num = num / len(VALID_CHARS) return string
https://github.com/mwolff44/django-simple-invoice/blob/ab14d905a69f37cd27e137c039750e6630bce4ef/invoice/utils/friendly_id.py#L89-L105
convert string to number
python
def isNumber(self, value): """ Validate whether a value is a number or not """ try: str(value) float(value) return True except ValueError: return False
https://github.com/CI-WATER/mapkit/blob/ce5fbded6af7adabdf1eec85631c6811ef8ecc34/mapkit/RasterConverter.py#L1097-L1107
convert string to number
python
def make_number(num: str, repr_: str = None, speak: str = None): """ Returns a Number or Fraction dataclass for a number string """ if not num or is_unknown(num): return # Check CAVOK if num == 'CAVOK': return Number('CAVOK', 9999, 'ceiling and visibility ok') # type: ignore # Check special if num in SPECIAL_NUMBERS: return Number(repr_ or num, None, SPECIAL_NUMBERS[num]) # type: ignore # Create Fraction if '/' in num: nmr, dnm = [int(i) for i in num.split('/')] unpacked = unpack_fraction(num) spoken = spoken_number(unpacked) return Fraction(repr_ or num, nmr / dnm, spoken, nmr, dnm, unpacked) # type: ignore # Create Number val = num.replace('M', '-') val = float(val) if '.' in num else int(val) # type: ignore return Number(repr_ or num, val, spoken_number(speak or str(val)))
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/core.py#L104-L125
convert string to number
python
def fmt_number(p): """Format a number. It will be printed as a fraction if the denominator isn't too big and as a decimal otherwise. """ formatted = '{:n}'.format(p) if not config.PRINT_FRACTIONS: return formatted fraction = Fraction(p) nice = fraction.limit_denominator(128) return ( str(nice) if (abs(fraction - nice) < constants.EPSILON and nice.denominator in NICE_DENOMINATORS) else formatted )
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/fmt.py#L202-L219
convert string to number
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 string to number
python
def tostring(self, cnf): """Convert Cnf object ot Dimacs cnf string cnf: Cnf object In the converted Cnf there will be only numbers for variable names. The conversion guarantees that the variables will be numbered alphabetically. """ self.varname_dict = {} self.varobj_dict = {} varis = set() for d in cnf.dis: for v in d: varis.add(v.name) ret = "p cnf %d %d" % (len(varis), len(cnf.dis)) varis = dict(list(zip(sorted(list(varis)),list(map(str,list(range(1,len(varis)+1))))))) for v in varis: vo = Variable(v) self.varname_dict[vo] = varis[v] self.varobj_dict[varis[v]] = vo for d in cnf.dis: ret += "\n" vnamelist = [] for v in d: vnamelist.append(("-" if v.inverted else "") + varis[v.name]) ret += " ".join(vnamelist) + " 0" return ret
https://github.com/netom/satispy/blob/0201a7bffd9070441b9e82187348d61c53922b6b/satispy/io/dimacs_cnf.py#L18-L51
convert string to number
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 string to number
python
def parse_number_from_substring(substring) -> Optional[float]: ''' Returns the number in the expected string "N:12.3", where "N" is the key, and "12.3" is a floating point value For the temp-deck or thermocycler's temperature response, one expected input is something like "T:none", where "none" should return a None value ''' try: value = substring.split(':')[1] if value.strip().lower() == 'none': return None return round(float(value), GCODE_ROUNDING_PRECISION) except (ValueError, IndexError, TypeError, AttributeError): log.exception('Unexpected argument to parse_number_from_substring:') raise ParseError( 'Unexpected argument to parse_number_from_substring: {}'.format( substring))
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/drivers/utils.py#L31-L48
convert string to number
python
def to_number(obj): ''' Cast an arbitrary object or sequence to a number type ''' if isinstance(obj, LiteralWrapper): val = obj.obj elif isinstance(obj, Iterable) and not isinstance(obj, str): val = next(obj, None) else: val = obj if val is None: #FIXME: Should be NaN, not 0 yield 0 elif isinstance(val, str): yield float(val) elif isinstance(val, node): yield float(strval(val)) elif isinstance(val, int) or isinstance(val, float): yield val else: raise RuntimeError('Unknown type for number conversion: {}'.format(val))
https://github.com/uogbuji/amara3-xml/blob/88c18876418cffc89bb85b4a3193e5002b6b39a6/pylib/uxml/uxpath/ast.py#L112-L132
convert string to number
python
def convert_str2num(unicode_str # type: Union[AnyStr, int, float, List[Union[AnyStr, float, int]], Tuple[Union[AnyStr, float, int]]] ): # type: (...) -> Union[AnyStr, int, float, List[Union[AnyStr, float, int]], Tuple[Union[AnyStr, float, int]]] """Convert string to string, integer, or float. Support tuple or list. Examples: >>> StringClass.convert_str2num('1.23') 1.23 >>> StringClass.convert_str2num(u'1.23') 1.23 >>> StringClass.convert_str2num(u'21.') 21 >>> StringClass.convert_str2num('abc123') 'abc123' >>> StringClass.convert_str2num((123, u'2.3', 3., 'abc', u'edf')) (123, 2.3, 3, 'abc', 'edf') >>> StringClass.convert_str2num([123, u'2.3', 3., 'abc', u'edf']) [123, 2.3, 3, 'abc', 'edf'] """ if MathClass.isnumerical(unicode_str): unicode_str = float(unicode_str) if unicode_str % 1. == 0.: unicode_str = int(unicode_str) return unicode_str elif is_string(unicode_str): return str(unicode_str) elif isinstance(unicode_str, tuple): return tuple(StringClass.convert_str2num(v) for v in unicode_str) elif isinstance(unicode_str, list): return list(StringClass.convert_str2num(v) for v in unicode_str) else: return unicode_str
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/utils.py#L387-L418
convert string to number
python
def punToEnglish_number(number): """Thee punToEnglish_number function will take a string num which is the number written in punjabi, like ੧੨੩, this is 123, the function will convert it to 123 and return the output as 123 of type int """ output = 0 #This is a simple logic, here we go to each digit and check the number and compare its index with DIGITS list in alphabet.py for num in number: output = 10 * output + DIGITS.index(num) return output
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/punjabi/numerifier.py#L8-L16
convert string to number
python
def as_number(as_number_val): """Convert AS Number to standardized asplain notation as an integer.""" as_number_str = py23_compat.text_type(as_number_val) if "." in as_number_str: big, little = as_number_str.split(".") return (int(big) << 16) + int(little) else: return int(as_number_str)
https://github.com/napalm-automation/napalm/blob/c11ae8bb5ce395698704a0051cdf8d144fbb150d/napalm/base/helpers.py#L336-L343
convert string to number
python
def str2int(num, radix=10, alphabet=BASE85): """helper function for quick base conversions from strings to integers""" return NumConv(radix, alphabet).str2int(num)
https://github.com/django-treebeard/django-treebeard/blob/8042ee939cb45394909237da447f8925e3cc6aa3/treebeard/numconv.py#L113-L115
convert string to number
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 string to number
python
def reduce_number(num): """Reduces the string representation of a number. If the number is of the format n.00..., returns n. If the decimal portion of the number has a repeating decimal, followed by up to two trailing numbers, such as: 0.3333333 or 0.343434346 It will return just one instance of the repeating decimals: 0.3 or 0.34 """ parts = str(num).split(".") if len(parts) == 1 or parts[1] == "0": return int(parts[0]) else: match = _REPEATING_NUMBER_TRIM_RE.search(parts[1]) if match: from_index, _ = match.span() if from_index == 0 and match.group(2) == "0": return int(parts[0]) else: return Decimal(parts[0] + "." + parts[1][:from_index] + match.group(2)) else: return num
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/data_table.py#L12-L45
convert string to number
python
def date_to_number(self, date): """ Converts a date or datetime instance to a corresponding float value. """ if isinstance(date, datetime.datetime): delta = date - self._null_date elif isinstance(date, datetime.date): delta = date - self._null_date.date() else: raise TypeError(date) return delta.days + delta.seconds / (24.0 * 60 * 60)
https://github.com/mila/pyoo/blob/1e024999f608c87ea72cd443e39c89eb0ba3cc62/pyoo.py#L1776-L1786
convert string to number
python
def _number_parser(str_to_number_func): """Return a function to parse numbers.""" def _parse_number_value(element_text, state): value = None try: value = str_to_number_func(element_text) except (ValueError, TypeError): state.raise_error(InvalidPrimitiveValue, 'Invalid numeric value "{}"'.format(element_text)) return value return _parse_number_value
https://github.com/gatkin/declxml/blob/3a2324b43aee943e82a04587fbb68932c6f392ba/declxml.py#L1531-L1544
convert string to number
python
def three_digit(number): """ Add 0s to inputs that their length is less than 3. :param number: The number to convert :type number: int :returns: String :example: >>> three_digit(1) '001' """ number = str(number) if len(number) == 1: return u'00%s' % number elif len(number) == 2: return u'0%s' % number else: return number
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/utils.py#L167-L188
convert string to number
python
def _formatNumbers(self, line): """ Format the numbers so that there are commas inserted. For example: 1200300 becomes 1,200,300. """ # below thousands separator syntax only works for # python 2.7, skip for 2.6 if sys.version_info < (2, 7): return line last_index = 0 try: # find the index of the last } character last_index = (line.rindex('}') + 1) end = line[last_index:] except ValueError: return line else: # split the string on numbers to isolate them splitted = re.split("(\d+)", end) for index, val in enumerate(splitted): converted = 0 try: converted = int(val) # if it's not an int pass and don't change the string except ValueError: pass else: if converted > 1000: splitted[index] = format(converted, ",d") return line[:last_index] + ("").join(splitted)
https://github.com/rueckstiess/mtools/blob/a6a22910c3569c0c8a3908660ca218a4557e4249/mtools/mlogfilter/mlogfilter.py#L141-L172
convert string to number
python
def word(value, digits=2): ''' Converts a large number to a formatted number containing the textual suffix for that number. :param value: number >>> print(word(1)) 1 >>> print(word(123456789)) 123.46 million ''' convention = locale.localeconv() decimal_point = convention['decimal_point'] decimal_zero = re.compile(r'%s0+' % re.escape(decimal_point)) prefix = value < 0 and '-' or '' value = abs(int(value)) if value < 1000: return u''.join([ prefix, decimal_zero.sub('', _format(value, digits)), ]) for base, suffix in enumerate(LARGE_NUMBER_SUFFIX): exp = (base + 2) * 3 power = 10 ** exp if value < power: value = value / float(10 ** (exp - 3)) return ''.join([ prefix, decimal_zero.sub('', _format(value, digits)), ' ', suffix, ]) raise OverflowError
https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/number.py#L137-L174
convert string to number
python
def _numToTwoByteString(value, numberOfDecimals=0, LsbFirst=False, signed=False): """Convert a numerical value to a two-byte string, possibly scaling it. Args: * value (float or int): The numerical value to be converted. * numberOfDecimals (int): Number of decimals, 0 or more, for scaling. * LsbFirst (bol): Whether the least significant byte should be first in the resulting string. * signed (bol): Whether negative values should be accepted. Returns: A two-byte string. Raises: TypeError, ValueError. Gives DeprecationWarning instead of ValueError for some values in Python 2.6. Use ``numberOfDecimals=1`` to multiply ``value`` by 10 before sending it to the slave register. Similarly ``numberOfDecimals=2`` will multiply ``value`` by 100 before sending it to the slave register. Use the parameter ``signed=True`` if making a bytestring that can hold negative values. Then negative input will be automatically converted into upper range data (two's complement). The byte order is controlled by the ``LsbFirst`` parameter, as seen here: ====================== ============= ==================================== ``LsbFirst`` parameter Endianness Description ====================== ============= ==================================== False (default) Big-endian Most significant byte is sent first True Little-endian Least significant byte is sent first ====================== ============= ==================================== For example: To store for example value=77.0, use ``numberOfDecimals = 1`` if the register will hold it as 770 internally. The value 770 (dec) is 0302 (hex), where the most significant byte is 03 (hex) and the least significant byte is 02 (hex). With ``LsbFirst = False``, the most significant byte is given first why the resulting string is ``\\x03\\x02``, which has the length 2. """ _checkNumerical(value, description='inputvalue') _checkInt(numberOfDecimals, minvalue=0, description='number of decimals') _checkBool(LsbFirst, description='LsbFirst') _checkBool(signed, description='signed parameter') multiplier = 10 ** numberOfDecimals integer = int(float(value) * multiplier) if LsbFirst: formatcode = '<' # Little-endian else: formatcode = '>' # Big-endian if signed: formatcode += 'h' # (Signed) short (2 bytes) else: formatcode += 'H' # Unsigned short (2 bytes) outstring = _pack(formatcode, integer) assert len(outstring) == 2 return outstring
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L1219-L1277
convert string to number
python
def cast_float(x): """ Attempt to cleanup string or convert to number value. :param any x: :return float: """ try: x = float(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#L43-L57
convert string to number
python
def cfnumber_to_number(cfnumber): """Convert CFNumber to python int or float.""" numeric_type = cf.CFNumberGetType(cfnumber) cfnum_to_ctype = {kCFNumberSInt8Type: c_int8, kCFNumberSInt16Type: c_int16, kCFNumberSInt32Type: c_int32, kCFNumberSInt64Type: c_int64, kCFNumberFloat32Type: c_float, kCFNumberFloat64Type: c_double, kCFNumberCharType: c_byte, kCFNumberShortType: c_short, kCFNumberIntType: c_int, kCFNumberLongType: c_long, kCFNumberLongLongType: c_longlong, kCFNumberFloatType: c_float, kCFNumberDoubleType: c_double, kCFNumberCFIndexType: CFIndex, kCFNumberCGFloatType: CGFloat} if numeric_type in cfnum_to_ctype: t = cfnum_to_ctype[numeric_type] result = t() if cf.CFNumberGetValue(cfnumber, numeric_type, byref(result)): return result.value else: raise Exception( 'cfnumber_to_number: unhandled CFNumber type %d' % numeric_type)
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/cocoapy.py#L1032-L1055
convert string to number
python
def int_to_charset(val, charset): """ Turn a non-negative integer into a string. >>> int_to_charset(0, B40_CHARS) '0' >>> int_to_charset(658093, B40_CHARS) 'abcd' >>> int_to_charset(40, B40_CHARS) '10' >>> int_to_charset(149190078205533, B40_CHARS) 'muneeb.id' >>> int_to_charset(-1, B40_CHARS) Traceback (most recent call last): ... ValueError: "val" must be a non-negative integer. """ if val < 0: raise ValueError('"val" must be a non-negative integer.') if val == 0: return charset[0] output = "" while val > 0: val, digit = divmod(val, len(charset)) output += charset[digit] # reverse the characters in the output and return return output[::-1]
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/b40.py#L37-L65
convert string to number
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 string to number
python
def convert(self, amount: Number, currency: str, to: str, reverse: bool=False) -> Number: """Convert amount to another currency""" rate = self.get_rate_for(currency, to, reverse) if self.return_decimal: amount = Decimal(amount) return amount * rate
https://github.com/budacom/trading-bots/blob/8cb68bb8d0b5f822108db1cc5dae336e3d3c3452/trading_bots/contrib/converters/base.py#L76-L81
convert string to number
python
def format_value(value,number_format): "Convert number to string using a style string" style,sufix,scale = decode_format(number_format) fmt = "{0:" + style + "}" + sufix return fmt.format(scale * value)
https://github.com/ptav/django-simplecrud/blob/468f6322aab35c8001311ee7920114400a040f6c/simplecrud/format.py#L80-L86