Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set a function parameter as a string in python?

def count(string,letter):
    count=0
    for each in string:
        if each==letter:
            count=count+1
    print count

is there a way to set the parameters to automatically accept the inputs as strings so the user doesn't have to add the quotations?

like image 367
Vikas Rajasekaran Avatar asked Dec 08 '25 07:12

Vikas Rajasekaran


1 Answers

I think you're asking if you can call the function like this:

count(this is my string, i)  # 3

instead of like this:

count('this is my string', 'i')  # 3

And the answer is that there is no way to do this. The arguments are parsed when the source code is parsed and the source code parser would have no way to disambiguate a string with commas in it from multiple input arguments.

Of course, this is just one example of parser ambiguity. If a feature like that were to be proposed, I suppose that if you were really strict in the format of the input strings (no commas, extra syntax to disambiguate strings that have variable names from strings that didn't, etc) you could probably come up with a syntax to make it work. However, remembering all of that would be much more difficult than just enclosing your strings in quotes as they're meant to be (and it would make the python parser much more cumbersome to work with). So all in all, I would think it would be a net-loss for the language for them to introduce a feature like that (though I'm just one person who isn't the BDFL so don't mistake my opinion for the opinion of someone who matters).

like image 128
mgilson Avatar answered Dec 09 '25 19:12

mgilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!