比较字符串中的字符

 偏偏喜欢你_Jerry_207 发布于 2023-02-12 10:12

给定两个字符串作为参数返回true如果第一个字可以通过改变一个字母从第二个字形成.我接近这个的方式是:

def differ(word_one, word_two):
    '''(str, str) -> bool

    Returns true iff word_two can be formed from word_one by changing
    exactly one letter.

    >>> differ('cat', 'bat')
    True
    >>> differ('word', 'sword')
    False

    '''
    temp_list = []
    # If the length of the first string is equal to the length of the
    # second string, iterate over the letters in the first string and
    # if the letter in the first string does not equal to the letter 
    # in the second string append the letter to temp_list
    if len(word_one) == len(word_two):
        for char in word_one:
            if char != word_two[word_one.index(char)]:
                temp_list.append(char)
    if len(temp_list) == 1:
        return True
    else:
        return False

根据描述,我的代码似乎工作得很好,但有一个更简化的方法吗?

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有