2017-09-15 99 views
-2

遺憾回國,但我是新來的Python,有一個問題。我如何創建一個函數,例如使用字符串「26355」,但只返回「6」?因爲它只會返回一個值,如果給函數的字符串有6個字符? 謝謝。蟒蛇功能 - 以一個字符串,只有某些字符

+1

你能解釋一下如何6快到了..? –

回答

0

您可以使用下面的函數

def return_wanted_string(inp_str, wanted_str): 
    return (wanted_str if wanted_str in inp_str else "Not found") 
0

其中一個方法可以是 -

def search(input_string, matching_char): 
    if input_string.index(matching_char) >= 0: 
     return input_string 
    return None 

以上功能可以在這種情況下,被稱爲

search("26355", "6") 

將返回「26355」

+0

嘿傢伙謝謝你的回覆,我不知道是否有人回答了這個問題,但如果給出的字符串有多個6呢?我怎麼能拿字符串「263396」,並只返回字符串「66」? – verdy

0
def custom_function(string_word, specific_word): 
    if specific_word in string_word: 
     return specific_word 
    else: 
     return 'Nothing Find' 

In [25]: custom_function('26343','6') 
Out[25]: '6' 
In [26]: custom_function('2343','6') 
Out[26]: 'Nothing Find' 

這是解決問題最簡單的方法。

0

你可以做到這樣 -

def func(input_str, input_char): 
    if input_char in input_str: 
     return input_char 
    return None 
  • 如果找到字符,則返回
  • 如果角色未找到函數返回無
0

你可以使用Python filter()命令如下:

print filter(lambda x: x == '6', '26355') 
print filter(lambda x: x == '6', '263396') 

這將使你:

6 
66 
0

這將工作:

number = "123456786960" 
want = "6" 
"".join([i for i in number if i == want])