there are lines:

n = 'babab' m = 'metot' 

new_str = 'MeToT' result: new_str = 'MeToT'

that is, if the letter 'b' in the first line, in the same place in line m letter should increase the register.

 new_str = (m[0].upper() + m[1] + m[2].upper() + m[3] + m[4].upper()) 

- this is not appropriate, since the places 'b' depend on the text entered by the user.

    3 answers 3

     m = 'metot' n = 'babab' new_str = '' for i in range(len(m)): new_str += m[i].upper() if n[i] == 'b' else m[i] print(new_str) 
    • one
      new_str+= can lead to quadratic instead of linear O (n) execution time. - jfs
     >>> ''.join([a.upper() if b == 'b' else a for a, b in zip('metot', 'babab')]) 'MeToT' 

    If the data in the numpy arrays:

     >>> a[b==b'b'[0]] &= 0x5f # upper mask >>> a.tostring() b'MeToT' 

    where a for example:

     >>> numpy.frombuffer(b'metot', dtype=numpy.uint8) array([109, 101, 116, 111, 116], dtype=uint8) 

    If the input characters are in the ascii range, this can be noticeably faster for large lines.

      Here is a primitive and certainly not the most effective solution:

       In [77]: new_str = ''.join([m[i] if c!='b' else m[i].upper() for i,c in enumerate(n)]) In [78]: new_str Out[78]: 'MeToT' 

      Starmap + zip solution:

       In [86]: from itertools import starmap In [87]: ''.join(starmap(lambda x,y: y if x!='b' else y.upper(), zip(n,m))) Out[87]: 'MeToT' 
      • If you have to start lambda, then it is better to use list comprehension instead of map + lambda. - jfs
      • @jfs, I agree. The first solution uses list comprehension , and in the second I decided to "play around" with a new function;) - MaxU
      • If you play, then map already supports several arguments: ''.join(map(lambda x,y: y if x!='b' else y.upper(), 'babab', 'metot')) - jfs
      • @jfs, did not know, thank you - MaxU February