S
S
ShagolChannel2022-01-18 09:42:05
Python
ShagolChannel, 2022-01-18 09:42:05

Is it possible to change the called functions depending on the content of the string?

I can't really describe what I want, but I'll try.

def num(Number):
   if Number == 1:
       print("Hi")
    elif Number == 2:
       print("hello")
    elif Number == 1 2 3;
        print("Hi hello nice" )
    elif Number == 1-3:
        print("Hi-nice")


Is it possible to somehow optimize such code so that there are not many conditions and is it possible to implement such code at all?

Is it possible to implement this

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mikhail Krostelev, 2022-01-18
@twistfire92

In general, such things are done through a dictionary.
If you just want to make a template string, then you can use replace via replace, bypassing all the key-value pairs in your dictionary.

d = {1: 'Hi', 2: 'hello', 3: 'nice'}

def foo(s):
    for key, value in d.items():
        s = s.replace(str(key), value)
    print(s)

foo('1')
foo('2')
foo('1 2 3')
foo('1-3')

just don't mess with data types.

M
MinTnt, 2022-01-18
@MinTnt

d = {"1": 'Hi', "2": 'hello', "3": 'nice'}
trans_table = str.maketrans(d)

s = "1 2 3"

print(s.translate(trans_table))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question