【问题标题】:How to replace characters in a string of 0's and 1's by other characters [duplicate]如何用其他字符替换0和1字符串中的字符[重复]
【发布时间】:2019-11-22 09:53:53
【问题描述】:

我正在尝试编写一个函数,该函数接受 1 和 0 的字符串并将 1 替换为“。”和带有“_”的 0

我不知道如何存储新字符串并在之后打印

def transform (x):
    text = ''
    for i in range(x):
        if i == 1:  
            i = "."
            text += i
        else:
            i = "_"
            text += i
    return text

transform(10110)

【问题讨论】:

  • 请注意10110 不是字符串而是数字。你应该改写transform('10110')。此外,要遍历字符,它应该是for i in x:,而不是range。还有一个小错误,但你应该可以自己找到它。

标签: python string replace


【解决方案1】:

这是一种方法:直接循环字符串,然后根据if 语句添加._。确保您使用i == '1',因为您的输入是一个字符串。您无需在if 语句中修改i 的值。

def transform(x):
    text = ''
    for i in x:
        if i == '1':
            text += "."  # directly add the `.`
        else:
            text += "_"  # directly add the `_`
    return text

transform('11001010') # call the function
# print (transform('11001010'))

# '..__._._'

【讨论】:

  • 对,我明白了。谢谢!
猜你喜欢
  • 2018-08-01
  • 2017-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多