i want to print string(given as input) as number(o/p) and i did it in c using switch case .i want to do the same in python...
wat if python provides switch case??n do we have equivalent of it in python??

Examle:
input:three hundred and fifty(string)
output:350(number)

Dani AI

Generated

A quick follow-up to : 's dictionary trick is a perfectly fine "switch" substitute when you have a small fixed set of phrases. For converting arbitrary spelled-out English numbers into numeric values, a small parser is more practical. The function below is a compact, self-contained parser that handles units, tens, "hundred", large scales (thousand, million, ...), negatives, and a spoken decimal introduced by "point".

def words_to_num(s):
    """
    Convert English number words to int or float.
    Handles basic tens/units, 'hundred', larger scales, optional 'point' decimals,
    and leading 'minus'/'negative'. Raises ValueError on unknown words.
    """
    units = {
        'zero':0,'one':1,'two':2,'three':3,'four':4,'five':5,'six':6,'seven':7,'eight':8,'nine':9,
        'ten':10,'eleven':11,'twelve':12,'thirteen':13,'fourteen':14,'fifteen':15,'sixteen':16,'seventeen':17,'eighteen':18,'nineteen':19
    }
    tens = {'twenty':20,'thirty':30,'forty':40,'fifty':50,'sixty':60,'seventy':70,'eighty':80,'ninety':90}
    scales = {'hundred':100,'thousand':1000,'million':10**6,'billion':10**9,'trillion':10**12}

    def _parse_int(tokens):
        total = 0
        current = 0
        for tok in tokens:
            if tok == 'and':
                continue
            if tok in units:
                current += units[tok]
            elif tok in tens:
                current += tens[tok]
            elif tok == 'hundred':
                if current == 0:
                    current = 1
                current *= scales['hundred']
            elif tok in scales:
                if current == 0:
                    current = 1
                current *= scales[tok]
                total += current
                current = 0
            else:
                raise ValueError("Unknown word: " + tok)
        return total + current

    s = s.lower().strip().replace('-', ' ').replace(',', ' ')
    if not s:
        raise ValueError("Empty input")
    sign = 1
    if s.startswith('minus ') or s.startswith('negative '):
        sign = -1
        s = s.split(' ', 1)[1]
    if 'point' in s:
        int_part, frac_part = s.split('point', 1)
    else:
        int_part, frac_part = s, None

    int_tokens = [t for t in int_part.split() if t]
    int_value = _parse_int(int_tokens) if int_tokens else 0

    if frac_part:
        frac_tokens = [t for t in frac_part.strip().split() if t]
        if all(t in units for t in frac_tokens):
            digits = ''.join(str(units[t]) for t in frac_tokens)
        else:
            digits = str(_parse_int(frac_tokens))
        frac_value = float('0.' + digits) if digits else 0.0
        return sign * (int_value + frac_value)

    return sign * int_value

Notes and tips: normalize input (the function replaces hyphens and commas and ignores "and"); add a pre-step to replace "a hundred" with "one hundred" if you expect that wording. This parser does not convert ordinals ("first" -> 1) or currency words; extend it by mapping ordinals to cardinals or stripping currency tokens first. For production use you can also consider existing packages (search for Python "word to number" libraries) if you need full localization and edge-case coverage. If the input domain is small and known, stick with the simple dict dispatch that suggested.

Recommended Answers

All 2 Replies

In Python a dictionary is used to implement a switch/case statement ...

# a dictionary switch/case like statement to replace
# multiple if/elif/else statements in Python

def switch_case(case):
    return case + " --> " + {
    'one hundred' : '100',
    'two hundred' : '200',
    'three hundred and fifty' : '350'
    }.get(case, "no case available")


# test it
num_str = 'three hundred and fifty'
print(switch_case(num_str))

print(switch_case('one hundred'))

"""
my result -->
three hundred and fifty --> 350
one hundred --> 100
"""

thanx a lot vegaseat...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.