Rectangle 27 351

Python method to check if a string is a float:

def isfloat(value):
  try:
    float(value)
    return True
  except:
    return False
isConvertibleToFloat(value)
val                   isfloat(val) Note
--------------------  ----------   --------------------------------
""                    False        Blank string
"127"                 True         Passed string
True                  True         Pure sweet Truth
"True"                False        Vile contemptible lie
False                 True         So false it becomes true
"123.456"             True         Decimal
"      -127    "      True         Spaces trimmed
"\t\n12\r\n"          True         whitespace ignored
"NaN"                 True         Not a number
"NaNanananaBATMAN"    False        I am Batman
"-iNF"                True         Negative infinity
"123.E4"              True         Exponential notation
".1"                  True         mantissa only
"1,234"               False        Commas gtfo
u'\x30'               True         Unicode is fine.
"NULL"                False        Null is not special
0x3fade               True         Hexidecimal
"6e7777777777777"     True         Shrunk to infinity
"1.797693e+308"       True         This is max value
"infinity"            True         Same as inf
"infinityandBEYOND"   False        Extra characters wreck it
"12.34.56"            False        Only one dot allowed
u''                  False        Japanese '4' is not a float.
"#56"                 False        Pound sign
"56%"                 False        Percent of what?
"0E0"                 True         Exponential, move dot 0 places
0**0                  True         0___0  Exponentiation
"-5e-5"               True         Raise to a negative number
"+1e1"                True         Plus is OK with exponent
"+1e1^5"              False        Fancy exponent not interpreted
"+1e1.3"              False        No decimals in exponent
"-+1"                 False        Make up your mind
"(1)"                 False        Parenthesis is bad

You think you know what numbers are? You are not so good as you think! Not big surprise.

convertibleToFloat

First of all this does not actually answer the question (wonder why people up-votes such answers). Second it assumes that the reader was surprised by the results, which need not be the case and from that assumption conclude that the reader is not as good as he thinks. It's rude to call people bad, it's worse when it's done on incorrect premises.

@skyking Your second point answers the first. The reason why it's been upvoted is because assuming people didn't know was spot on.

@skyking it was a TF2 joke, quoting the character called Heavy. The joke sailed so far over your head that you misinterpreted the detail on this work of art as a blemish when it fact it was the masterstroke. I marvel at how people can enjoy a free ride to mars and yet still moan bitterly about the inadequacy of the cup holders. You don't like it? Fine, show me how to do it better.

@skyring I up-voted the answer because it is an excellent summary of when python can parse strings into floats, and answers OP's more open-ended title question rather than his specific example. It serves the community of programmers well (which I think is the purpose of this website).

python - Parse String to Float or Int - Stack Overflow

python string parsing floating-point integer
Rectangle 27 347

Python method to check if a string is a float:

def isfloat(value):
  try:
    float(value)
    return True
  except:
    return False
isConvertibleToFloat(value)
val                   isfloat(val) Note
--------------------  ----------   --------------------------------
""                    False        Blank string
"127"                 True         Passed string
True                  True         Pure sweet Truth
"True"                False        Vile contemptible lie
False                 True         So false it becomes true
"123.456"             True         Decimal
"      -127    "      True         Spaces trimmed
"\t\n12\r\n"          True         whitespace ignored
"NaN"                 True         Not a number
"NaNanananaBATMAN"    False        I am Batman
"-iNF"                True         Negative infinity
"123.E4"              True         Exponential notation
".1"                  True         mantissa only
"1,234"               False        Commas gtfo
u'\x30'               True         Unicode is fine.
"NULL"                False        Null is not special
0x3fade               True         Hexidecimal
"6e7777777777777"     True         Shrunk to infinity
"1.797693e+308"       True         This is max value
"infinity"            True         Same as inf
"infinityandBEYOND"   False        Extra characters wreck it
"12.34.56"            False        Only one dot allowed
u''                  False        Japanese '4' is not a float.
"#56"                 False        Pound sign
"56%"                 False        Percent of what?
"0E0"                 True         Exponential, move dot 0 places
0**0                  True         0___0  Exponentiation
"-5e-5"               True         Raise to a negative number
"+1e1"                True         Plus is OK with exponent
"+1e1^5"              False        Fancy exponent not interpreted
"+1e1.3"              False        No decimals in exponent
"-+1"                 False        Make up your mind
"(1)"                 False        Parenthesis is bad

You think you know what numbers are? You are not so good as you think! Not big surprise.

convertibleToFloat

First of all this does not actually answer the question (wonder why people up-votes such answers). Second it assumes that the reader was surprised by the results, which need not be the case and from that assumption conclude that the reader is not as good as he thinks. It's rude to call people bad, it's worse when it's done on incorrect premises.

@skyking Your second point answers the first. The reason why it's been upvoted is because assuming people didn't know was spot on.

@skyking it was a TF2 joke, quoting the character called Heavy. The joke sailed so far over your head that you misinterpreted the detail on this work of art as a blemish when it fact it was the masterstroke. I marvel at how people can enjoy a free ride to mars and yet still moan bitterly about the inadequacy of the cup holders. You don't like it? Fine, show me how to do it better.

@skyring I up-voted the answer because it is an excellent summary of when python can parse strings into floats, and answers OP's more open-ended title question rather than his specific example. It serves the community of programmers well (which I think is the purpose of this website).

python - Parse String to Float or Int - Stack Overflow

python string parsing floating-point integer
Rectangle 27 1

Based on solution to the linked answer.

We can define next utility function using Dict.suggest method

def is_part_of_existing_word(string, words_dictionary):
    suggestions = words_dictionary.suggest(string)
    return any(string in suggestion
               for suggestion in suggestions)
>>> import enchant
>>> english_dictionary = enchant.Dict("en")
>>> is_part_of_existing_word('wat', words_dictionary=english_dictionary)
True
>>> is_part_of_existing_word('wate', words_dictionary=english_dictionary)
True
>>> is_part_of_existing_word('way', words_dictionary=english_dictionary)
True
>>> is_part_of_existing_word('wayt', words_dictionary=english_dictionary)
False
>>> is_part_of_existing_word('wayter', words_dictionary=english_dictionary)
False
>>> is_part_of_existing_word('wayterlx', words_dictionary=english_dictionary)
False
>>> is_part_of_existing_word('lackjack', words_dictionary=english_dictionary)
True
>>> is_part_of_existing_word('ucumber', words_dictionary=english_dictionary)
True

python - How to check to see if a string is contained in any english w...

python nlp pyenchant
Rectangle 27 2

if line.hasPrefix("#") {
  // checks to see if a string (line) begins with the character "#"
}

I don't know why this was down-voted... this is the simple Swift way of doing this. Most new iOS developers are probably going to be using Swift from here on out, and the OP never said that only Objective-C answers were requested.

"I don't know why this was down-voted"- probably because the syntax is wrong? Should be if line.hasPrefix("prefix") {}`

Thanks for pointing out a simpler syntax, but placing () around an if statement isn't bad syntax. For some of us old timers, it reads more clearly, and works exactly the same. if (line.hasPrefix("#")) {} works just as well.

iphone - How to see if an NSString starts with a certain other string?...

iphone objective-c
Rectangle 27 3

All numbers are floats in Javascript. Note that the type name is in quotes, it's a string, and it's all lower case. Also note that typeof is an operator, not a function, no need for parens (though they're harmless).

floating point - How can I check to see if a value is a float in javas...

javascript floating-point typeof
Rectangle 27 1

The second is radically different, but I think you'll find it's much more simple.

boolean containmentCheck(String big, String small) {
    return big.contains(small);
}

The lesson to be learned here is: Read the API very carefully.

Thanks this would work for me only if I could use .contains(); . and we havent learned break; yet.

@JeffTeague Well, you have learned it now. break will exit while, for and do loops in advance. It should be said that there is any number of ways this could be done.

How to see if a string is a substring. Java - Stack Overflow

java string for-loop netbeans substring
Rectangle 27 17

Your question is incorrect; the error you see is not a result of how you built python, but of a confusion between byte strings and unicode strings.

Byte strings (e.g. "foo", or 'bar', in python syntax) are sequences of octets; numbers from 0-255. Unicode strings (e.g. u"foo" or u'bar') are sequences of unicode code points; numbers from 0-1112064. But you appear to be interested in the character , which (in your terminal) is a multi-byte sequence that represents a single character.

ord(u'')
>>> [ord(x) for x in u'']

That tells you which sequence of code points "" represents. It may give you [233], or it may give you [101, 770].

chr()
unichr()
>>> unichr(233)
u'\xe9'

This character may actually be represented either a single or multiple unicode "code points", which themselves represent either graphemes or characters. It's either "e with an acute accent (i.e., code point 233)", or "e" (code point 101), followed by "an acute accent on the previous character" (code point 770). So this exact same character may be presented as the Python data structure u'e\u0301' or u'\u00e9'.

Most of the time you shouldn't have to care about this, but it can become an issue if you are iterating over a unicode string, as iteration works by code point, not by decomposable character. In other words, len(u'e\u0301') == 2 and len(u'\u00e9') == 1. If this matters to you, you can convert between composed and decomposed forms by using unicodedata.normalize.

The Unicode Glossary can be a helpful guide to understanding some of these issues, by pointing how how each specific term refers to a different part of the representation of text, which is far more complicated than many programmers realize.

'' does not necessarily represent a single code point. It could be two code points (U+0065 + U+0301).

Each abstract character is always represented by a single code point. However, code points may be encoded to multiple bytes, depending on the encoding scheme. i.e., '' is two bytes in UTF-8 and UTF-16, and four bytes in UTF-32, but it is in each case still a single code point U+00E9.

@Ben Blank: U+0065 and U+0301 are code points and they do represent '' which can also be represented by U+00E9. Google "combining acute accent".

J.F. is right about combining U+0065 and U+0301 to form '' but this is not a reversible functino. You will get U+00E9. According to wikipedia, these composite code points are useful for backwards compatibility

@teehoo - It is a reversible function in the sense that you may re-normalize the code point representing the composed character into a sequence of code points representing the same composed character. In Python you can do this like so: unicodedata.normalize('NFD', u'\xe9').

How to check if a string in Python is in ASCII? - Stack Overflow

python string unicode ascii
Rectangle 27 17

Your question is incorrect; the error you see is not a result of how you built python, but of a confusion between byte strings and unicode strings.

Byte strings (e.g. "foo", or 'bar', in python syntax) are sequences of octets; numbers from 0-255. Unicode strings (e.g. u"foo" or u'bar') are sequences of unicode code points; numbers from 0-1112064. But you appear to be interested in the character , which (in your terminal) is a multi-byte sequence that represents a single character.

ord(u'')
>>> [ord(x) for x in u'']

That tells you which sequence of code points "" represents. It may give you [233], or it may give you [101, 770].

chr()
unichr()
>>> unichr(233)
u'\xe9'

This character may actually be represented either a single or multiple unicode "code points", which themselves represent either graphemes or characters. It's either "e with an acute accent (i.e., code point 233)", or "e" (code point 101), followed by "an acute accent on the previous character" (code point 770). So this exact same character may be presented as the Python data structure u'e\u0301' or u'\u00e9'.

Most of the time you shouldn't have to care about this, but it can become an issue if you are iterating over a unicode string, as iteration works by code point, not by decomposable character. In other words, len(u'e\u0301') == 2 and len(u'\u00e9') == 1. If this matters to you, you can convert between composed and decomposed forms by using unicodedata.normalize.

The Unicode Glossary can be a helpful guide to understanding some of these issues, by pointing how how each specific term refers to a different part of the representation of text, which is far more complicated than many programmers realize.

'' does not necessarily represent a single code point. It could be two code points (U+0065 + U+0301).

Each abstract character is always represented by a single code point. However, code points may be encoded to multiple bytes, depending on the encoding scheme. i.e., '' is two bytes in UTF-8 and UTF-16, and four bytes in UTF-32, but it is in each case still a single code point U+00E9.

@Ben Blank: U+0065 and U+0301 are code points and they do represent '' which can also be represented by U+00E9. Google "combining acute accent".

J.F. is right about combining U+0065 and U+0301 to form '' but this is not a reversible functino. You will get U+00E9. According to wikipedia, these composite code points are useful for backwards compatibility

@teehoo - It is a reversible function in the sense that you may re-normalize the code point representing the composed character into a sequence of code points representing the same composed character. In Python you can do this like so: unicodedata.normalize('NFD', u'\xe9').

How to check if a string in Python is in ASCII? - Stack Overflow

python string unicode ascii
Rectangle 27 154

Although there are a bunch of correct answers above, it should be noted that the String object in JavaScript has a native .trim() method as of ECMAScript 5. Thus ideally any attempt to prototype the trim method should really check to see if it already exists first.

if(!String.prototype.trim){  
  String.prototype.trim = function(){  
    return this.replace(/^\s+|\s+$/g,'');  
  };  
}

Trim string in JavaScript? - Stack Overflow

javascript string trim
Rectangle 27 154

Although there are a bunch of correct answers above, it should be noted that the String object in JavaScript has a native .trim() method as of ECMAScript 5. Thus ideally any attempt to prototype the trim method should really check to see if it already exists first.

Although there are a bunch of correct answers above, it should be noted that the String object in JavaScript has a native .trim() method as of ECMAScript 5. Thus ideally any attempt to prototype the trim method should really check to see if it already exists first.

if(!String.prototype.trim){  
  String.prototype.trim = function(){  
    return this.replace(/^\s+|\s+$/g,'');  
  };  
}
if(!String.prototype.trim){  
  String.prototype.trim = function(){  
    return this.replace(/^\s+|\s+$/g,'');  
  };  
}

Trim string in JavaScript? - Stack Overflow

javascript string trim
Rectangle 27 154

Although there are a bunch of correct answers above, it should be noted that the String object in JavaScript has a native .trim() method as of ECMAScript 5. Thus ideally any attempt to prototype the trim method should really check to see if it already exists first.

if(!String.prototype.trim){  
  String.prototype.trim = function(){  
    return this.replace(/^\s+|\s+$/g,'');  
  };  
}

Trim string in JavaScript? - Stack Overflow

javascript string trim
Rectangle 27 154

Although there are a bunch of correct answers above, it should be noted that the String object in JavaScript has a native .trim() method as of ECMAScript 5. Thus ideally any attempt to prototype the trim method should really check to see if it already exists first.

if(!String.prototype.trim){  
  String.prototype.trim = function(){  
    return this.replace(/^\s+|\s+$/g,'');  
  };  
}

Trim string in JavaScript? - Stack Overflow

javascript string trim
Rectangle 27 4

Check to see IF the string's length is a multiple of 4. Aftwerwards use this regex to make sure all characters in the string are base64 characters.

\A[a-zA-Z\d\/+]+={,2}\z

If the library you use adds a newline as a way of observing the 76 max chars per line rule, replace them with empty strings.

The link mentioned shows 404. Please check and update.

Sorry @AnkurKumar but that's what happen when people have uncool URLs: they change all the time. I have no idea where it's moved to. I hope you find other useful resources through Google

How to check whether the string is base64 encoded or not - Stack Overf...

base64
Rectangle 27 3

As a more general answer, try using the hasPrefix method. For example, the code below checks to see if a string begins with 10, which is the error code used to identify a certain problem.

NSString* myString = @"10:Username taken";

if([myString hasPrefix:@"10"]) {
      //display more elegant error message
}

objective c - How to check if NSString begins with a certain character...

objective-c nsstring
Rectangle 27 6

If you want to use regular expression you can use as below,

public static boolean isNumeric(String str)
{
  return str.matches("-?\\d+(\\.\\d+)?");  //match a number with optional '-' and decimal.
}

Try-and catching an excpetion has such a huge overhead though.

java - How to check if a string is numeric? - Stack Overflow

java
Rectangle 27 11

Don't include quotes around your true/false. This value is not a string!

Thanks, that did the trick! Sorry it took so long to accept your solution, got sidetracked. See edit for my revised PHP, if you're interested. :)

Two and a half years later, your comment solved my problem. Namely, the fact that the True False are not strings. Thanks :)

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

php - FullCalendar not displaying time from JSON events - Stack Overfl...

php json fullcalendar
Rectangle 27 11

Don't include quotes around your true/false. This value is not a string!

Thanks, that did the trick! Sorry it took so long to accept your solution, got sidetracked. See edit for my revised PHP, if you're interested. :)

Two and a half years later, your comment solved my problem. Namely, the fact that the True False are not strings. Thanks :)

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

php - FullCalendar not displaying time from JSON events - Stack Overfl...

php json fullcalendar
Rectangle 27 77

You have to be carefull when using Boolean.valueOf(string) or Boolean.parseBoolean(string). The reason for this is that the methods will always return false if the String is not equal to "true" (the case is ignored).

Boolean.valueOf("YES") -> false

Because of that behaviour I would recommend to add some mechanism to ensure that the string which should be translated to a Boolean follows a specified format.

if (string.equalsIgnoreCase("true") || string.equalsIgnoreCase("false")) {
    Boolean.valueOf(string)
    // do something   
} else {
    // throw some exception
}

This is the best example I've seen and what should have been implemented in the Boolean type to begin with. Throwing an exception for invalid Boolean value is important for many applications.

No thats not totally true. here is the underlying implementation of parseBoolean public static boolean parseBoolean(String s) { return ((s != null) && s.equalsIgnoreCase("true")); }

java - How to convert String object to Boolean Object? - Stack Overflo...

java string boolean
Rectangle 27 9

If you really want to make sure that a string contains only a number, any number (integer or floating point), and exactly a number, you cannot use parseInt()/ parseFloat(), Number(), or !isNaN() by themselves. Note that !isNaN() is actually returning true when Number() would return a number, and false when it would return NaN, so I will exclude it from the rest of the discussion.

The problem with parseFloat() is that it will return a number if the string contains any number, even if the string doesn't contain only and exactly a number:

parseFloat("2016-12-31")  // returns 2016
parseFloat("1-1") // return 1
parseFloat("1.2.3") // returns 1.2

The problem with Number() is that it will return a number in cases where the passed value is not a number at all!

Number("") // returns 0
Number(" ") // returns 0
Number(" \u00A0   \t\n\r") // returns 0

The problem with rolling your own regex is that unless you create the exact regex for matching a floating point number as Javascript recognizes it you are going to miss cases or recognize cases where you shouldn't. And even if you can roll your own regex, why? There are simpler built-in ways to do it.

However, it turns out that Number() (and isNaN()) does the right thing for every case where parseFloat() returns a number when it shouldn't, and vice versa. So to find out if a string is really exactly and only a number, call both functions and see if they both return true:

function isNumber(str) {
  if (typeof str != "string") return false // we only process strings!
  // could also coerce to string: str = ""+str
  return !isNaN(str) && !isNaN(parseFloat(str))
}

This returns true when the string has leading or trailing spaces. ' 1', '2 ' and ' 3 ' all return true.

Adding something like this to the return-statement would solve that: && !/^\s+|\s+$/g.test(str)

validation - Is there a (built-in) way in JavaScript to check if a str...

javascript validation numeric
Rectangle 27 7

/**
 * Check if a number is a counting number by checking if it
 * is an integer primitive type, or if the string represents
 * an integer as a string
 */
function is_int_val($data) {
    if (is_int($data) === true) return true;
    if (is_string($data) === true && is_numeric($data) === true) {
        return (strpos($data, '.') === false);
    }
}

rather than scatter my code with little utility functions, I'd rather have something that's built into php.

I don't like these hacks either. But using this approach or ctype suggestion by Dominic, you're going to encapsulate all implementation anyway in a method. When using php, I always have an "Util" class to address these problems.

elseif can just be if because you've already returned in the statement above it.

php - How to check that a string is an int, but not a double, etc.? - ...

php string casting types int