Home > Software engineering >  python split strings (even odd)
python split strings (even odd)

Time:10-05

I want to take an even string and change the front half and the string and the back half of the string. I want to be able to do the same with an odd number but keep the middle letter of the string the same. Ive coded for the even number but I get an integer output instep of the new string

def split_and_join (my_string):
    a = len('my_string')
    if (a % 2) == 0:
        first_half  = a[:len(a)//2]
        second_half = a[len(a)//2:]
        modified_string = join.s(second_half, first_half)
    else:
        print(a)
        
if __name__ == '__main__':
    my_string = input("Enter string:")
    print((split_and_join)(my_string))

CodePudding user response:

Try this;

def split_and_join(my_string):
    a = len(my_string)
    if (a % 2) == 0:
        first_half  = my_string[:a//2]
        second_half = my_string[a//2:]
        modified_string = second_half   first_half
        return modified_string
    else:
        first_half  = my_string[:a//2]
        second_half = my_string[a//2 1:]
        modified_string = second_half   my_string[a//2]   first_half
        return modified_string
        
if __name__ == '__main__':
    my_string = input("Enter string:")
    print((split_and_join)(my_string))

# If input; "sachin" then code's output: "hinsac"
# If input; "kohli" then code's output: "lihko"

CodePudding user response:

You could do it like this:

def split_and_join(my_string):
    e = (_len := len(my_string)) // 2
    return my_string[e:]   my_string[:e] if _len % 2 == 0 else my_string[e 1:]   my_string[e]   my_string[:e]

print(split_and_join('abcd'))
print(split_and_join('abcde'))

Output:

cdab
decab

CodePudding user response:

here is the solution :

def split_and_join (my_string):
    a = len(my_string)
    first_half  = my_string[:a//2]
    second_half = my_string[a//2:]
    modified_string = f"{second_half}{first_half}"
    print(modified_string)

        
if __name__ == '__main__':
    my_string = input("Enter string:")
    split_and_join(my_string)
  • Related