简体   繁体   中英

python string replace using for loop with if else

I am new with python, trying to replace string using for loop with if else condition, I have a string and want to replace some character of that string in a such way that it should take / pick first character of the string and search them in the old_list if the character match it should replace that character with the character of new_list and if the character does not match it should consider that character (previous) and the next character together of the string and search them combinely and again search in old_list and so on.

it should replace in this oder (picking the character from string) = 010,101,010,010,100,101,00,00,011,1101,011,00,101,010,00,011,1111,1110,00,00,00,010,101,010, replacing value = 1001,0000,0000,1000,1111,1001,1111,1111,100,1010101011,100,1111,1001,0000,1111,100,10100101,101010,1111,1111,1111,0000,1001,

with the example of above string if we performed that operation the string will becomes final or result string = 10010000000010001111100111111111100101010101110011111001000011111001010010110101011111111111100001001

string = 01010101001010010100000111101011001010100001111111110000000010101010
old_list = ['00','011','010','101','100','1010','1011','1101','1110','1111']
new_list = ['1111','100','0000','1001','1000'1111','0101','1010101011','101010','10100101']

i = 0
for i in range((old), 0):
    if i == old:
        my_str = my_str.replace(old[i],new[i], 0)
    else:
        i = i + 1

print(my_str)

as result, string become = 10010000000010001111100111111111100101010101110011111001000011111001010010110101011111111111100001001

new = ['a ','local ','is ']
my_str = 'anindianaregreat'
old = ['an','indian','are']

for i, string in enumerate(old):
    my_str = my_str.replace(string, new[i], 1)

print(my_str)

Your usage of range is incorrect.

range goes from lower (inclusive) to higher (exclusive) or simply 0 to higher (exclusive)

Your i == old condition is incorrect as well. ( i is an integer, while old is a list). Also what is it supposed to do?

You can simply do:

for old_str, new_str in zip(old, new):
    my_str = my_str.replace(old_str, new_str, 1)

https://docs.python.org/3/library/stdtypes.html#str.replace You can provide an argument to replace to specify how many occurrences to replace.

No conditional is required since if old_str is absent, nothing will be replaced anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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