简体   繁体   中英

Converting string using list in python

I've been trying to rearrange the string by reversing a particular strings consecutively from the given string input and the limit is given as input.

for example limit is 3

if input is Hellothegamestarts

output must be Heltolhegemastastr and it is saved in separate array The code is:

while True: 
    t = int(input())
    if t == 0:
        break

    string = raw_input()
    string = string.encode('utf-8')
    leng = len(string)
    r = t/leng
    m = []
    leng = 0

    for i in range(r):
        if r % 2 == 0:
            l = 0
            l = leng + t
            for i in range(t):
                temp = string[l]
                m.append(temp)
                l = l - 1
            r = r + 1


            leng = leng + t

        else:
            l = 0
            l = leng

            for i in range(t):
                temp = string[l]
                m.append(temp)
                l = l + 1

            r = r + 1


            leng = leng + t


    print m

the output i got is [] and asks for next input for t.

Any help is appreciated.

Take the blocks in chunks of 3s, and reverse the odd ones, eg:

import re

s = 'Hellothegamestarts'
r = ''.join(
    el if idx % 2 == 0 else el[::-1] 
    for idx, el in enumerate(re.findall('.{,3}', s))
)
# Heltolhegemastastr

Maybe you can try -

t = int(input())
if t == 0:
    break;

string = raw_input()
m = ''
leng = len(string)
i = 0
while i < leng:
    if (i/t) % 2 != 0:
        m = m + string[i+t-1:i-1:-1]
    else:
        m = m + string[i:i+t]
    i = i + t
print(m)

Alternatively you can try this

def  myfunc(s, count):
     return [''.join(x) for x in zip(*[list(s[z::count]) for z in range(count)])]

a='Hellothegamestarts'
lst=myfunc(a,3)
print "".join([i if lst.index(i) in range(0,len(lst),2) else i[::-1] for i in lst])

myfun i didn't write it.It's from here

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