尝试将特定位置的字符串中的字符设置为另一个字符

时间:2016-11-18 02:58:18

标签: python python-3.x

我想在不使用索引的情况下尝试这样做。

def SSet(s, i, c):
#A copy of the string 's' with the character in position 'i'
#set to character 'c'
count = -1
for item in s:
    if count >= i:
        count += 1
    if count == i:
        item += c 
print(s)

print(SSet("Late", 3, "o"))

在本例中,Late应更改为Lato。

谢谢。

2 个答案:

答案 0 :(得分:1)

您没有累加器来保持输出,并且计数器上的逻辑已关闭。以下循环遍历字符串并将字符连接到输出,除非字符索引是指定它使用给定字符的索引。

def SSet(s, i, c):
    """A copy of the string 's' with the character in position 'i' set to character 'c'"""
    res = ""
    count = -1
    for item in s:
        count += 1
        if count == i:
            res += c
        else:
            res += item
    return res

print(SSet("Late", 3, "o"))

打印

Lato

使用枚举删除计数器可以更好地编写:

def SSet(s, i, c):
    """A copy of the string 's' with the character in position 'i' set to character 'c'"""
    res = ""
    for index, item in enumerate(s):
        if index == i:
            res += c
        else:
            res += item
    return res

也可以通过将字符附加到列表然后在最后加入它们来加快速度:

def SSet(s, i, c):
    """A copy of the string 's' with the character in position 'i' set to character 'c'"""
    res = []
    for index, item in enumerate(s):
        if index == i:
            res.append(c)
        else:
            res.append(item)
    return ''.join(res)

它也没有用,但这里是如何用切片做的:

def SSet(s, i, c):
    """A copy of the string 's' with the character in position 'i' set to character 'c'"""
    return s[:i]+c+s[i+1:]

答案 1 :(得分:1)

def SSet(s, i, c):
#A copy of the string 's' with the character in position 'i'
#set to character 'c'
    count = 0
    strNew=""
    for item in s:
        if count == i:
            strNew=strNew+c
        else:
            strNew=strNew+item
        count=count+1

    return strNew

print(SSet("Late", 3, "o"))