TransWikia.com

Split a string based on a delimiter but shift across 1

Stack Overflow Asked by Adam Sewell on August 28, 2020

I trying to split a string (although numbers currently a string in df column) but am struggling to find an answer anywhere. I think using expressions might be the way forward but haven’t quite got my head around them.

example 1) 12.540%

example 2) 4.555.6%

I would like to take everything to the left of the first ‘.’ and only one number going to the right of the same first ‘.’

I need to apply it to all different number lengths and the above statement is the only constant.

example 1 ) 12.5 and 40%

example 2) 4.5 and 55.6%

Thank you

3 Answers

The following function should do what you want:

def split_string(num):
  s=num.split('.', 1)
  s1=s[0]+'.'+s[1][0]
  s2=s[1][1:]
  return (s1, s2)

Correct answer by archer on August 28, 2020

If you want regular expressions, catch the groups using this.

^(d+..)(.*)$

Use this with either re.search if you want.

b = re.search(r'^(d+..)(.*)$', string)
b.group(1)
b.group(2)

Ex-

val = '12.445.6'
b = re.search(r'^(d+..)(.*)$', val)
b.group(1)
Out[24]: '12.4'
b.group(2)
Out[25]: '45.6'

Answered by Anurag Reddy on August 28, 2020

This is a straightforward problem in string manipulation. Any string tutorial will teach you the basic operations.

  1. Find the location of the period.
  2. Add 1.
  3. Split the string at that point: grab one slice through that index; a second slice from there to the end.

For instance, one you find the location loc and adjust 1 or 2 spots to the right:

num, pct = str[:loc], str[loc:]

Answered by Prune on August 28, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP