Gennaro
Gennaro

Reputation: 113

Split a string in two on the middle comma?

I want to split a string into 2 parts based on the middle comma.

From:

"1, 4, a, fdsa, 53, dfs, sdfg, klk"

To:

"1, 4, a, fdsa" and "53, dfs, sdfg, klk"

Upvotes: 1

Views: 1906

Answers (4)

riyasyash
riyasyash

Reputation: 183

Let your sting be input_str, then

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.

Upvotes: 0

Stefan Pochmann
Stefan Pochmann

Reputation: 28606

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')

Upvotes: 1

user7986928
user7986928

Reputation:

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 ,). To do this, we can apply the string method .find.

S.find(',') will return 1. (since the first , is at index 1)

S.find(',', 2) will return 4. (since after the 3rd character on your string, the first , is at index 4)

Let the number of , in the string be 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 ,. You may use S.count(',') to find the number of ,'s (this will be n).

Let the location (or index) be m. So that after this, you can create two strings : A=S[0:m-1]; and B=S[m+1:]; to produce the desired split.

Hope this helps.

Upvotes: 1

kabanus
kabanus

Reputation: 25895

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(...).strip()

Upvotes: 4

Related Questions