0

I need to scan a long string to determine numbers and put commas after every number. But digits are not the same and randomly changes.

little sample = 14 194 180 119 195 213 175 220 133 24 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 72 288 319 345 275 145 5

Here is what I tried so far

for i in range(len(my_values)):
if my_values[i] in (range(999)):
    my_values[i] = ","

But It gave me strange output

['0', '\t', '0', '\t', '0', '\t', '0', '\t', '0', '\t', '1', '2', '5', '\t', '2', '7', '1', '\t', '3', '0', '8', '\t',

Note: isdigit or isNumeric functions are valid for one character. They did not work. What should I change to add commas on string after randomly changes number?

3
  • 1
    ",".join(my_values.split()) Commented Apr 14, 2020 at 17:02
  • Is the string composed of numbers separated by spaces? Commented Apr 14, 2020 at 17:02
  • @DarrylG Yes. It is read from text file But I don't think reading part causes the challenge Commented Apr 14, 2020 at 17:03

2 Answers 2

1

You can simply try to break the string based on spaces/tab and combine the obtained elements using a comma:

new_str = ",".join(my_values.split(' '))    #or '\t' if they are separated by a tab
Sign up to request clarification or add additional context in comments.

2 Comments

Best use just .split(), without an argument.
@Błotosmętek Agreed!
0

You can get all numbers as:

>>> import re
>>> a = re.findall('-?\d+\.?\d*', sample)
>>> a
['14', '194', '180', '119', '195', '213', '175', '220', '133', '24', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '72', '288', '319', '345', '275', '145', '5']

and then join as:

>>> ", ".join(a)
'14, 194, 180, 119, 195, 213, 175, 220, 133, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 72, 288, 319, 345, 275, 145, 5'
>>> 

5 Comments

Thanks!. It did work. Can you explain what '\d+' part is doing?
Its a regular expression to extract number with 1 or more digits. Do accept the answer if its working for you.
I will :). There is a time duration. Thanks again
This works assuming there are no negative nor fractional numbers in the string.
What if negative numbers also exist? Should we scan again?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.