[英]Split a string in two on the middle comma?
I want to split a string into 2 parts based on the middle comma. 我想根据中间逗号将字符串分成2部分。
From: 从:
"1, 4, a, fdsa, 53, dfs, sdfg, klk"
To: 至:
"1, 4, a, fdsa" and "53, dfs, sdfg, klk"
Some basic arithmetic: 一些基本的算法:
splitstring = mystring.split(',')
print(','.join(splitstring[:len(splitstring)//2]) + ' and ' + ','.join(splitstring[len(splitstring)//2:]))
In case you want to eliminate extra spaces from the original string after the middle comma you can just strip them, so add to each join
statement: 如果您想在中间逗号后消除原始字符串中的多余空格,可以去除它们,因此添加到每个
join
语句中:
','.join(...).strip()
Regards. 问候。 I will use your string as example :
我将以您的字符串为例:
S = "1, 4, a, fdsa, 53, dfs, sdfg, klk"
Assuming that the number of ,
will be odd. 假设的数目
,
将是奇数。 So, my idea is to locate the middle ,
(this would be the (n+1)th ,
). 所以,我的想法是找到中间
,
(这将是(N + 1)个 ,
)。 To do this, we can apply the string method .find
. 为此,我们可以应用字符串方法
.find
。
S.find(',')
will return 1
. S.find(',')
将返回1
。 (since the first ,
is at index 1
) (由于第一
,
是在索引1
)
S.find(',', 2)
will return 4
. S.find(',', 2)
将返回4
。 (since after the 3rd character on your string, the first ,
is at index 4
) (因为你的字符串中的第3个字符之后,第一个
,
是在指数4
)
Let the number of ,
in the string be 2n+1 . 让数量
,
字符串中是2N + 1。 Since you don't know the location of the middle ,
(for other strings) you can use loop as many as (n+1) times to locate the index of the middle ,
. 既然你不知道中间的位置
,
(对于其他字符串),你可以使用循环多达(N + 1)倍来定位中间的指数,
。 You may use S.count(',')
to find the number of ,
's (this will be n ). 您可以使用
S.count(',')
发现的数量,
(这将是N)的。
Let the location (or index) be m
. 令位置(或索引)为
m
。 So that after this, you can create two strings : A=S[0:m-1];
这样一来,您就可以创建两个字符串:
A=S[0:m-1];
and B=S[m+1:];
和
B=S[m+1:];
to produce the desired split. 产生所需的分割。
Hope this helps. 希望这可以帮助。
Just splitting and rejoining the first half. 只是分裂并重新加入上半场。
>>> s = '1, 4, a, fdsa, 53, dfs, sdfg, klk'
>>> *a, b = s.split(', ', s.count(',') // 2 + 1)
>>> ', '.join(a), b
('1, 4, a, fdsa', '53, dfs, sdfg, klk')
Let your sting be input_str, then 让你的刺痛是input_str,然后
s = input_str.split(',')
string_length = len(s)
print(','.join(s[0:string_length//2]) +" and " + ','.join(s[string_length//2:]))
will print what you need. 将打印您所需要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.