简体   繁体   English

如何只接受 Python function 中的一些字符串?

[英]How can I accept only some strings in Python function?

I want to make it like this:我想让它像这样:

>>> myfunc("strawberry")
ok
# myfunc only works with strawberry

I know that most people will answer with:我知道大多数人会回答:

def myfunc(something):
   if something == "strawberry":
      print("ok")

But I want to do all this in the parameter setting.但我想在参数设置中完成这一切。
Like, kind of like this:就像,有点像这样:

def myfunc(something: OnlyThese["strawberry", "cake"]:
   print("ok")

Although the code above is very incorrect, I want to see if Python already has a feature like this.虽然上面的代码很不正确,但是我想看看Python是否已经有这样的功能。

Don't believe there is a way to do what you are wanting to do without writing code in the function body.不要相信没有在 function 主体中编写代码的情况下可以做你想做的事情。

I found answers to a similar question at我在以下位置找到了类似问题的答案

enforce arguments to a specific list of values 将 arguments 强制执行到特定的值列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何编写一个只接受内部带有 int 或 float 类型的列表的 Python 函数? - How can I write a Python function that will only accept a list with int or float type inside? 当只有一些变量需要多个变量时,如何将多个值传递给函数-Python 3 - How can I pass multiple values to a function when only some variables need more than one - python 3 如何在 function 中使用 r(用于原始数据)作为 Python 中的字符串? - How can I use the r(for raw data)for strings in Python in a function? 如何在Python中组合多个函数的输出(字符串)? - How can I combine multiple function's output(strings) in Python? 我应该如何更改此函数,使其可以在Python 2和Python 3中整齐地处理字符串和unicode? - How should I change this function such that it can neatly handle strings and unicode in both Python 2 and in Python 3? 如何在 Python3 中接受灵活的日期? - How can I accept flexible dates in Python3? 我怎么能猜出已知字符串哈希中缺少的字符? - How can i guess some missing character in known strings hash? 如何比较python中的复杂字符串? - How can I compare complex strings in python? Python3 pop() 函数只删除字符串 - Python3 pop() function only deleting strings Python 初学者(需要帮助)-如何使 While 循环仅接受某些用户输入? - Python Beginner (need assistance) - How do I make a While loop only accept certain user inputs?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM