0

可変数の文字列を取り、各文字列を調べて に置き換える関数を定義し/ます-。そしてそれらを元に戻します。(ここに私の論理的な問題があります - 何を返しますか?)

def replace_all_slash(**many):
    for i in many:
        i = i.replace('/','-')
    return many

それが正しいか?文字列を別々の文字列として再び思い出すにはどうすればよいですか?

呼び出し例:

 allwords = replace_all_slash(word1,word2,word3)

しかしallwords、関数を呼び出す前と同じように、別の文字列にする必要があります。これを行う方法?

私は理解することが明確であることを願っています

4

4 に答える 4

3

使用したい*args(1 つ星) ではありません**args:

>>> def replace_all_slash(*words):
   return [word.replace("/", "-") for word in words]

>>> word1 = "foo/"
>>> word2 = "bar"
>>> word3 = "ba/zz"
>>> replace_all_slash(word1, word2, word3)
['foo-', 'bar', 'ba-zz']

次に、それらを同じ変数に再割り当てするには、割り当てのアンパック構文を使用します。

>>> word1
'foo/'
>>> word2
'bar'
>>> word3
'ba/zz'
>>> word1, word2, word3 = replace_all_slash(word1, word2, word3)
>>> word1
'foo-'
>>> word2
'bar'
>>> word3
'ba-zz'
于 2013-09-17T20:39:35.183 に答える
1

解決策 1: 新しいリストを作成し、次のことを追加します。

def replace_all_slash(*many):
    result = []
    for i in many:
        result.append(i.replace('/','-'))
    return result

リスト内包表記を使用した解決策 2:

def replace_all_slash(*many):
    return [i.replace('/','-') for i in many]
于 2013-09-17T20:30:42.767 に答える
1

関数を書き直す必要があります。

def replace_all_slash(*args):
    return [s.replace('/','-') for s in args]

次のように呼び出すことができます。

w1,w2,w3 = replace_all_slash("AA/","BB/", "CC/")
于 2013-09-17T20:39:18.583 に答える
0

呼び出しコードで引数を逆アセンブルするには、文字列ごとに変数が必要です。

word1,word2,word3 = replace_all_slash(word1,word2,word3) 
于 2013-09-17T20:37:46.433 に答える