简体   繁体   中英

Python - Iterate over String and adding characters in form of a target

I'm currently working on a programm which is meant to insert "(" and ")" to a string. The "(" and ")" have to find the center of the string. For Example:

w(o(r)l)d for an odd length or T(e(s(t( (T(es)t) )T)e)s)t for an even length. The first and last index is not supposed to be grated a ( or ). spaces have to be taken account of aswell, as shown in test test test.

Currently i have come up with this program:

text = "Test Test Test"
def target(text):
   if len(text) % 2 == 0:
      first_middle = int(len(text) / 2) - 1
      second_middle = int(len(text) / 2)
      text = ''.join('({}'.format(x) for x in text [1:first_middle])
      text = ''.join('{})'.format(x) for x in text [second_middle:])
   else:
      middle = int(len(text) / 2)
      text = ''.join('({}'.format(x) for x in text [0:middle])
      text = ''.join('{})'.format(x) for x in text [middle:-1])
   
   return text

print (target(text))

How can i solve the problem? It seems like i can not iterate with something like [0:middle]?

Your Help is greatly appreciated !

How about this?

def target(text):
    n = len(text)
    output = "(".join(text[:n//2])
    if n % 2 != 0:
        output += "("
    output += ")".join(text[n//2:])
    return output

>>> target("world")
'w(o(r)l)d'
>>> target("Test Test Test")
'T(e(s(t( (T(es)t) )T)e)s)t'

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