-2

I want to add space between number and text

Example string: ABC24.00XYZ58.28PQR

output: ABC 24.00 XYZ 58.28 PQR

Please let me know the answers.

Thanks a lot.

yatu
  • 80,714
  • 11
  • 64
  • 111
PRAYANK
  • 57
  • 8

4 Answers4

1

You could use re.sub back-referencing the captured group to add the spaces:

s = 'ABC24.00XYZ58.28PQR'

 re.sub('(\d+(\.\d+)?)', r' \1 ', s).strip()
# 'ABC 24.00 XYZ 58.28 PQR'

See demo

yatu
  • 80,714
  • 11
  • 64
  • 111
0

You can use re.split to separate the input string into a list of tokens. Then join all those tokens by a space.

import re

s = "ABC24.00XYZ58.28PQR"
split = [c for c in re.split(r'([-+]?\d*\.\d+|\d+)', s) if c]
result = " ".join(split)
print(result)

Output:

ABC 24.00 XYZ 58.28 PQR

The regex r'([-+]?\d*\.\d+|\d+)' should be fairly robust and detect floats of the type -12, +5.0 as well.

Lydia van Dyke
  • 2,308
  • 3
  • 11
  • 24
0

If there is no more requirements,you could use regex:

import re

s = "ABC24.00XYZ58.28PQR"
s = re.sub("[A-Za-z]+",lambda group:" "+group[0]+" ",s)
print(s.strip())
jizhihaoSAMA
  • 11,804
  • 9
  • 23
  • 43
  • You can back-reference the captured groups, as `\1`, see [here](https://stackoverflow.com/a/61184274/9698684) – yatu Apr 13 '20 at 09:00
-1

Concatenate string and converted number to string type:

print ("AB" + " "+ str(34)) //or
print ("AB " + str(34))

If you want to add spaces in string use Regex refer: python regex add space whenever a number is adjacent to a non-number