Python Forum

Full Version: calculating length of string
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
Dear All,

how can I calculate the length of the string, for e.g

   len(ontology)= 8

but I need it should return 1..... PLEASE TELL ME ANY COMMAND FOR IT IN PYTHON.....


THANK YOU IN ADVANCES
Are you saying you want the length of the string "ontology" to be one? Could you elaborate a bit on your question?
actually, I want to calculate a length of term

for e.g [information exchange]

len([information exchanhe])= 19

but I want it to return 2 instead 19 bcz two terms

len([ontology ])= 9

but i want it to return 1 bcz single term
A simple solution to this would be to split on spaces and get the length of that.

What's the context for this? A homework assignment? Or some other project?

In either case, if you write code giving it a try we're more likely to help along toward fully completing the code.
domain = "statistical"

split_domain = domain.split(" ")

for part in split_domain:
print(len(part))
returns 11 but i want 1
11
Do it this way:
domain = "statistical"

split_domain = domain.split(" ")

print(len(split_domain))
Please, use python code tags, when posting code. This helps preserve the indentation.
What you describe as desired result is number of words in the string, not length of the string itself. words being defined as one or more constitutive non-blank chars. what micseydel  suggest is the most simple approach.

>>> mystr = 'statistical'
>>> len(mystr.split(' '))
1
>>> mystr = 'some string'
>>> len(mystr.split(' '))
2
>>> mystr = 'yet another string'
>>> len(mystr.split(' '))
3
however you need to take into account multiple spaces, new line, etc.


>>> mystr = 'some   string'
>>> len(mystr.split(' '))
4
>>> print mystr.split(' ')
['some', '', '', 'string']
thank you ..............buran
(Feb-27-2017, 07:15 AM)buran Wrote: [ -> ]however you need to take into account multiple spaces, new line, etc.

split() without arguments will do just that:
Output:
>>> x='abcd   efgh\tijkl\n  mnopq' >>> print x abcd   efgh     ijkl   mnopq >>> x.split() ['abcd', 'efgh', 'ijkl', 'mnopq']
Regular expressions are cool sometimes, too:
>>> import re
>>> regex = re.compile(r"\s+")
>>> regex.split("hello there\tevery     body!")
['hello', 'there', 'every', 'body!']
Pages: 1 2