Message Boards Message Boards

0
|
6875 Views
|
3 Replies
|
2 Total Likes
View groups...
Share
Share this post:

Replacing NumberStrings with the Numbers

Posted 10 years ago

Hi everyone

I have a list (and sometimes an array) of strings, some of which are number strings:

listOfStrings = {"Not a number", "12.345", "Not this one either", "-934"};

I'd like to replace the number strings by their corresponding numbers. The fastest way I've found is using a plain old If statement

If[StringMatchQ[#, NumberString], 
   ToExpression[#], #] & /@ listOfStrings

A more complicated and slower way is to use StringCases and delete the excess baggage in the result:

DeleteCases[
 Flatten[StringCases[
   listOfStrings, {char : LetterCharacter .., 
     num : NumberString} :> {char, ToExpression[num]}]], Null | ""]

Just curious to know if there is a more direct way than either of these.

Gregory

POSTED BY: Gregory Lypny
3 Replies
Posted 10 years ago

Thanks for the tips, Gianluca and Sean,

I'll give both of these a whirl. I'm looking for speed as I have a lot of text to process.

Regards,

Gregory

POSTED BY: Gregory Lypny

Here is a very quick way of doing it:

Interpreter["Number" | "String"][listOfStrings]

This is an Interpreter that first tries to interpret something as a Number, but when that fails defaults to interpreting it as a String.

POSTED BY: Sean Clarke

This seems a little terser:

StringReplace[listOfStrings, str : NumberString :> ToExpression[str]]

but it is not faster, and you get the numbers wrapped in StringExpression, which you have to remove.

POSTED BY: Gianluca Gorni
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract