2014-12-07 18 views
2

我需要一個函數,它接受兩個字符串參數,並返回一個字符串只有在這兩個參數字符串中的字符。返回值中不應有重複的字符。python打印一個字符串中的常見項沒有重複

這是我,但我需要讓打印的事情只有一次,如果有更多的則是一個

def letter(x,z): 
    for i in x: 
     for f in z: 
      if i == f: 
       s = str(i) 
       print(s) 
+0

不知道這是否屬於更多的代碼審查... – 2014-12-07 22:18:47

+0

@jmendeth如果他們已經工作(這顯然不是) – Dannnno 2014-12-07 22:21:54

+0

要清楚你是否正在返回一些東西或者你在印刷什麼,或者都?你可以使用哪些語言功能? (我覺得這是一個家庭作業問題) – Dannnno 2014-12-07 22:22:43

回答

1

試試這個

s = set() 

def letter(x,z): 
    for i in x: 
     for f in z: 
      if i == f: 
       s.add(i) 


letter("hello","world") 
print("".join(s)) 

它將打印'ol'

5

如果順序不重要,可以取各字中字符set的交點&,然後join將其設置爲單個字符串並return它。

def makeString(a, b): 
    return ''.join(set(a) & set(b)) 

>>> makeString('sentence', 'santa') 
'nts' 
+0

也'''.join(set(a))。intersection(b)' – 2014-12-07 22:26:51

+0

@gnibbler是'intersection'與一個字符串/更低效率? – Wolf 2014-12-07 22:43:35

+0

@Cyber​​也許你最好開始你的答案*試試這個* ;-) – Wolf 2014-12-07 22:50:54

1

如果set s爲不是你出於某種原因(也許你想保留一個或另一個字符串的順序包,請嘗試:

def common_letters(s1, s2): 
    unique_letters = [] 
    for letter in s1: 
     if letter in s2 and letter not in unique_letters: 
      unique_letters.append(letter) 

    return ''.join(unique_letters) 

print(common_letters('spam', 'arthuprs')) 

(假設的Python 3爲print()

+0

print()在Python 2.6以上版本中工作正常..它是「正確的」方法來處理事情,因爲從Python2轉換到Python3時不會導致問題。 – 2014-12-07 22:55:32

相關問題