简体   繁体   中英

Replacing characters from string one to string two

I need to create a function that takes the parameters (character, stringOne, stringTwo). The function returns a new word which contain the same data as stringTwo + whatever characters in stringOne in the same position.

Example:

  • stringOne = "apple"
  • stringTwo = "12345"
  • character = "p"
  • Should Return "1pp45"

I am lost on how I should proceed.

def replace(char, word1, word2):
newWord = ""
for s in range(len(word1)):
    if word1[s] == char:
return

Continuing what you have done, using simple for-loop and ternary operation, this is how it can be done:

def replace(char, word1, word2):
    newWord = ""
    for s in range(len(word1)):
        newWord += char if word1[s] == char else word2[s]
    return newWord

Which is equivalent to:

def replace(char, word1, word2):
    newWord = ""
    for s in range(len(word1)):
        if word1[s] == char:
            newWord += char
        else:
            newWord += word2[s]
    return newWord

Just in case you are not familiar with ternary operation.

Here's how to modify your existing code so that it does what you want. I've changed newWord to new_word to conform with the standard Python style convention.

def replace(char, word1, word2):
    new_word = ""
    for i in range(len(word2)):
        if word1[i] == char:
            new_word += char
        else:
            new_word += word2[i]
    return new_word

# Test
print(replace("p", "apple", "12345"))    

output

1pp45

Note that this code will raise an IndexError: string index out of range exception if word1 is shorter than word2 .

There are various better ways to implement this function. Firstly, we can use the zip function to iterate over the characters of both strings in parallel. This is a bit cleaner than your indirect iteration using the indices of the strings to access the characters.

def replace(char, word1, word2):
    new_word = ""
    for c1, c2 in zip(word1, word2):
        if c1 == char:
            new_word += char
        else:
            new_word += c2
    return new_word

Note that if the strings aren't the same length then zip will stop gracefully when the shorter string finishes.

We can make that code more compact by replacing the if... else block with a conditional expression.

def replace(char, word1, word2):
    new_word = ""
    for c1, c2 in zip(word1, word2):
        new_word += char if c1 == char else c2
    return new_word

A more advanced version uses a list comprehension to build a list of the desired characters and the string .join method to convert that list into a string.

def replace(char, word1, word2):
    return ''.join([char if c1 == char else c2 
        for c1, c2 in zip(word1, word2)])

It's also possible to do this using a generator expression.

''.join(char if c1 == char else c2 for c1, c2 in zip(word1, word2))

However that's less efficient than using a list comprehension, due to the way that .join works. .join has to scan its argument twice: the first scan is used to calculate the total size of the output string, the second scan does the actual joining. But you can't scan a generator twice, so if you pass .join a generator it has to build a temporary list from the generator.

You can also use a list comprehension, iterate and replace.

>>> x, y, c = 'apple', '12345', 'p'              
>>> ''.join([c if x[i] == c else s for i, s in enumerate(y)])
'1pp45'

Pythonic way:

>>> stringOne = "apple" 
>>> stringTwo = "12345"
>>> my_char = "p"
>>> "".join([x[1] if my_char!=x[0] else x[0] for x in zip(stringOne, stringTwo)])
'1pp45'
def replace(char, word1, word2):
    newWord= list(word2)
    for counter in range(min(len(word1), len(word2))):
            if word1[counter]== char:
                    newWord[counter]= char
    return "".join(newWord)

The simplest solution would be to iterate through characters of word1 and if a character match is found with the character that we are interested in finding, then we replace the character at that index in word2.

def replace(char, word1, word2):
    newWord = ""
    word2List = list(word2)
    # Check is character is present in word1
    # and if length of word1 and word2 are equal
    if char not in word1 or len(word1) != len(word2):
        return False
    else:
        for i,c in enumerate(word1):
            if c == char:
                word2List[i] = c



    # Converting list back to string
    return ''.join(word2List)

print(replace('p','apple','12345'))

Output:

1pp45

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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