简体   繁体   English

如何访问函数python中的字符串?

[英]How do I access the string inside my function python?

Trying to gain access to this string to test it if it has 3 or more blues "b" inside of it. 尝试访问此字符串以测试它是否具有3个或更多的蓝色“ b”。 ---Both test and three_or_more_blues are functions.----- I'm completely lost, any one got an idea? --- test和three_or_more_blues都是函数。-----我完全迷失了,有人知道吗? Please change my title if it doesn't fit my question. 如果不符合我的问题,请更改标题。 Not sure really how to ask the question. 真的不确定如何问这个问题。 Thanks! 谢谢!

test(three_or_more_blues, "brrrrrbrrrrrb")

You could use .count(). 您可以使用.count()。

sentence = 'brrrrrbrrrrrb'
amount = sentence.count('b')
print(amount)

And then you could use a loop to calculate your next step. 然后,您可以使用循环来计算下一步。

if (amount >= 3): 
    # Do something

Assuming test is a function that takes a function and a string as paramters, and three_or_more_blues is a function that returns true if its string parameter has 3 or more 'b' characters, then 假设test是一个将一个函数和一个字符串作为参数的函数, three_or_more_blues是一个函数,如果其字符串参数具有3个或更多'b'字符,则返回true

def test(func, str):
    if func(str):
        # do something with str

test(three_or_more_blues, "brrrrrbrrrrrb")

I am not sure if I understand you correctly - you are asking how to pass the string 'brrrrrbrrrrrb' to the three_or_more_blues function? 我不确定我是否理解正确-您正在问如何将字符串'brrrrrbrrrrrb'传递给three_or_more_blues函数?

If that is the case, than you just simply pass it when you call the three_or_more_blues function like this: 如果真是这样,那么您只需在调用three_or_more_blues函数时像下面那样简单地传递它即可:

def test(func, some_string):
    func(some_string)  # here you call the passed function

# if three_or_more_blues would look like this:
def three_or_more_blues(some_string):
    print "Yes, 3 or more b's" if some_string.count('b') >= 0 else "No"

# you would get this from your function call
test(three_or_more_blues, "brrrrrbrrrrrb")  # prints: "Yes, 3 or more b's"

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM