繁体   English   中英

如何修复此代码,使其打印一串字母,其中一个位置被相应的输入数字替换?

[英]How to fix this code so that it prints a string of letters with one of the positions replaced by a corresponding inputted number?

问题:

创建一个 function replaceCharAtPos(orig,pos),它接收两个输入参数,一个字符串 (orig) 和一个正 integer 数字 (pos)。

如果数字是字符串中的 position,则 function 应该返回一个新字符串。 新字符串应该是原始字符串,除了在 position pos 中的原始字符,它应该有 position 编号本身(如果 position 编号替换为数字,则部分字符应超过 1 个单位position 编号,例如,如果 position 编号为 12,则为 2)。

如果数字 pos 在原始字符串 orig 中不是有效的 position,则返回的字符串应与原始字符串完全相同。

应该输入和输出的示例:

print (replaceCharAtPos("abcd",2))

这给出了 output ab2d,因为数字 2 对应于字符串的索引 position 2(索引从 0 开始),因此它替换了“abcd”的“c”

我的代码有问题:

def replaceCharAtPos(orig,pos):
    if pos >= (len(orig)):
        return orig
    orig = list(orig)
    orig[pos] = str(pos)
    return ''.join(orig)

输入两位数时,例如 12,新字符串应采用 12 的第二个/最后一个数字,即 2。在下面查看我的代码问题:

print (replaceCharAtPos('abcdefghijklmn',12))

我得到的 output 是abcdefghijkl12n ,但它应该是abcdefghijkl2n 如何解决这个问题? 我尝试将str(pos)更改为str(pos[-1])但它不起作用。

谢谢

您可以在参数转换后的索引中使用[-1]索引,以确保在提供超过 1 个数字时它始终采用最后一个数字。 您几乎是正确的,但是您执行str(pos[-1])的方式是尝试将pos切片,它是integer而不是转换后的str

In [10]: def replace_char_at_idx(orig, idx): 
    ...:     if idx >= (len(orig)): 
    ...:         return orig 
    ...:     orig = list(orig) 
    ...:     # Take always the last digit from the CONVERTED 
    ...:     orig[idx] = str(idx)[-1] 
    ...:     return ''.join(orig) 


In [11]: replace_char_at_idx("abcdefghijklmn", 12)                                                                                                                                                                
Out[11]: 'abcdefghijkl2n'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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