【问题标题】:How to convert a function to be used as int in Python? or is that even possible?如何将函数转换为 Python 中的 int?或者这甚至可能吗?
【发布时间】:2016-10-24 20:44:35
【问题描述】:

问题: 我不能也不知道如何使用/将函数位置转换为函数 find_second 的输入/整数。


代码

  # Define a procedure, find_second, that takes
  # two strings as its inputs: a search string
  # and a target string. It should return a
  # number that is the position of the second
  # occurrence of the target string in the
  # search string.

def position (search_string, target):
    position_target = search_string.find(target)
    return int(position_target)

def find_second (search_string, second_target):
    return search_string.find(second_target, position+1)

danton = "De l'audace, encore de l'audace, toujours de l'audace"

print find_second(danton, 'audace')`

错误信息:

Traceback (most recent call last):
File "vm_main.py", line 33, in <module>
import main
File "/tmp/vmuser_laavqhjazh/main.py", line 19, in <module>
print find_second(danton, 'audace')
File "/tmp/vmuser_laavqhjazh/main.py", line 13, in find_second
return search_string.find(second_target, position+1)
TypeError: unsupported operand type(s) for +: 'function' and 'int'

【问题讨论】:

  • 大概,你想要position(search_string, second_target) + 1,可能有不同的论点?
  • 你需要真正调用这个函数。
  • @chepner 谢谢,成功了!! :P

标签: python function int


【解决方案1】:

位置是一个函数。另一种选择是:

def find_second(search_string, target):
    temp = search_string.find(target)
    return search_string.find(target, temp)

danton = "De l'audace, encore de l'audace, toujours de l'audace"

print find_second(danton, 'audace')`

【讨论】:

    猜你喜欢
    • 2019-05-30
    • 1970-01-01
    • 1970-01-01
    • 2011-05-20
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    相关资源
    最近更新 更多