Split a string into 2 in Python

前端 未结 6 763
轻奢々
轻奢々 2020-12-29 21:42

Is there a way to split a string into 2 equal halves without using a loop in Python?

相关标签:
6条回答
  • 2020-12-29 22:09
    firstpart, secondpart = string[:len(string)/2], string[len(string)/2:]
    
    0 讨论(0)
  • 2020-12-29 22:16

    In Python 3:
    If you want something like
    madam => ma d am
    maam => ma am

    first_half  = s[0:len(s)//2]
    second_half = s[len(s)//2 if len(s)%2 == 0 else ((len(s)//2)+1):]
    
    0 讨论(0)
  • 2020-12-29 22:21

    Another possible approach is to use divmod. rem is used to append the middle character to the front (if odd).

    def split(s):
        half, rem = divmod(len(s), 2)
        return s[:half + rem], s[half + rem:]
    
    frontA, backA = split('abcde')
    
    0 讨论(0)
  • 2020-12-29 22:22

    minor correction the above solution for below string will throw an error

    string = '1116833058840293381'
    firstpart, secondpart = string[:len(string)/2], string[len(string)/2:]
    

    you can do an int(len(string)/2) to get the correct answer.

    firstpart, secondpart = string[:int(len(string)/2)], string[int(len(string)/2):]

    0 讨论(0)
  • 2020-12-29 22:29

    Whoever is suggesting string[:len(string)/2], string[len(string)/2 is not keeping odd length strings in mind!

    This works perfectly. Verified on edx.

    first_half = s[:len(s)//2]

    second_half = s[len(s)//2:]

    0 讨论(0)
  • 2020-12-29 22:31
    a,b = given_str[:len(given_str)/2], given_str[len(given_str)/2:]
    
    0 讨论(0)
提交回复
热议问题