【问题标题】:s.replace string method, looping through a strings.replace 字符串方法,循环遍历一个字符串
【发布时间】:2019-09-24 17:15:59
【问题描述】:

我正在尝试编写一种方法,将第一个字母之后的每个字母替换为“*”而不是字母。 例子: "babble" 产生 "ba**le" "that" 产生 "tha*"

我的代码在循环时似乎与替换函数有问题,我不太明白为什么。

def fix_start(s):
    if len(s) < 2:
        s = "" 
    else:
        for i in s:
            if i == s[0]:
                if s[0]:
                    continue
                s.replace(s[i], "*")
                i += i
    print(s)

【问题讨论】:

  • replace 不会就地替换,它会返回一个新字符串。我没有检查你的其余代码,但你需要s = s.replace(...)
  • 这似乎没有奏效。
  • 如前所述,我没有检查您的其余代码,因此其中可能存在其他问题。

标签: python string if-statement replace iteration


【解决方案1】:

str.replace 方法返回原始字符串的副本,其中所有出现的给定子字符串都替换为给定的新字符串,因此您可以简单地从第二个字符切分输入字符串并将所有出现的第一个字符替换为'*',并将其连接在原始字符串的第一个字符之后:

def fix_start(s):
    return s[0] + s[1:].replace(s[0], '*')

这样fix_start('babble') 返回:'ba**le'

【讨论】:

    猜你喜欢
    • 2016-01-24
    • 2020-02-16
    • 1970-01-01
    • 2014-09-19
    • 2023-03-23
    • 1970-01-01
    • 2021-06-30
    • 2017-10-06
    相关资源
    最近更新 更多