1

I am trying to write a function that takes a string of 1 and 0 and replaces the 1 with "." and the 0 with "_"

I am not sure how to store the new string and print it afterwards

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

transform(10110)
Georgy
  • 12,464
  • 7
  • 65
  • 73
diana
  • 13
  • 2
  • Note that `10110` is not a string but a number. You should write `transform('10110')` instead. Also, to iterate over characters it should be `for i in x:`, without `range`. There is one more little mistake, but you should be able to find it by yourself. – Georgy Jul 12 '19 at 16:06

1 Answers1

1

This is one way: Loop over the string directly and then add the . or _ based on the if statement. Make sure you use i == '1' because your input is a string. You don't need to modify the value of i inside the if statements.

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'))

# '..__._._'
Sheldore
  • 37,862
  • 7
  • 57
  • 71