在 Python 中将字符串拆分为 2

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4789601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 17:31:59  来源:igfitidea点击:

Split a string into 2 in Python

pythonstringsplit

提问by Kiwie Teoh

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

有没有办法在不使用 Python 循环的情况下将字符串分成 2 个相等的一半?

采纳答案by Senthil Kumaran

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

回答by lalli

a,b = given_str[:len(given_str)/2], given_str[len(given_str)/2:]

回答by J. Lernou

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

另一种可能的方法是使用 divmod。rem 用于将中间字符附加到前面(如果是奇数)。

def split(s):
    half, rem = divmod(len(s), 2)
    return s[:half + rem], s[half + rem:]

frontA, backA = split('abcde')

回答by tHappy

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

在 Python 3 中:
如果你想要像
madam => ma这样的东西d上午
MAAM =>毫安时

first_half  = s[0:len(s)//2]
second_half = s[len(s)//2 if len(s)%2 == 0 else ((len(s)//2)+1):]

回答by som shubham sahoo

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.

你可以做一个int(len(string)/2)来得到正确的答案。

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

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