-3

I have a phrase like this:

a='Hello I have 4 ducks'

and I apply str.split to this, so I now I have

>>> a.split()
['Hello','I','have','4','ducks'].

the problem is that every a.split()[i] is a string, but I need the program to recognize that the 4 is an integer. I need this to know which position the first integer is in, so I do this:

if(isinstance(a[i], float) or isinstance(a[i], int)):
    punt=k

but every a[i] is a string.

Can I do something that makes my program recognize the integers inside this list?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • Have you looked into the other string methods? `str.isdigit` will probably be helpful. Or could you `try` the conversion to integer and handle failures on things like `'ducks'`? – jonrsharpe Jul 19 '16 at 08:28
  • So, there is a metod that acts like split() but recognizes the type of every part? Does str.isdigit do that? Thank you – Genís Algans Seguí Jul 19 '16 at 08:30
  • No, there isn't. You will have to implement that functionality yourself, but there are helpful methods to do it relatively easily. – jonrsharpe Jul 19 '16 at 08:31
  • Why is this question getting downvoted? Seems like a reasonable concept to me... – Jeff G Jul 19 '16 at 08:34
  • 1
    @JeffG the fact that it's received a cavalcade of crap answers in a few minutes suggests that it's the kind of thing the OP should have worked on themselves. – jonrsharpe Jul 19 '16 at 08:35
  • Thank you everyone! stack overflow teaches better than the teachers, and free...you all good people – Genís Algans Seguí Jul 19 '16 at 08:40

7 Answers7

0

You did not define the output you wish, thus I am not sure whether this is what you want, yet it works:

a='Hello I have 4 ducks'
a=a.split()
ints=[]
strings=[]
for part in a: 
    try: 
        ints.append(int(part))
    except:
        strings.append(part)

ints,strings

gives:

([4], ['Hello', 'I', 'have', 'ducks'])

If you want to have a list of types, then you can modify like this:

types = []
for part in a:
    try:
        int(part)
        types.append('int')
    except:
        types.append('string')

types    

which gives:

types

['string', 'string', 'string', 'int', 'string']
Nikolas Rieble
  • 2,416
  • 20
  • 43
0
demo_list = ['Hello','I','have','4','ducks']
i=0
for temp in demo_list:
    print temp
    if temp.isdigit():
        print "This is digit"
        print "It is present at location - ", i
    i=i+1

Output: This is digit.

It is present at location - 3

Dinesh Pundkar
  • 4,160
  • 1
  • 23
  • 37
0

You can define your own version of split(). Here i named it my_split().

def my_split(astring):
    return [find_type(x) for x in astring.split()]


def find_type(word):
    try:
        word_type = int(word)
    except ValueError:
        try:
            word_type = float(word)
        except ValueError:
            word_type = word
    return word_type

a = 'Hello I have 4 ducks weighing 3.5 kg each'

split_type = [x for x in my_split(a)]
print(split_type)
#['Hello', 'I', 'have', 4, 'ducks', 'weighing', 3.5, 'kg', 'each']
print([type(x) for x in my_split(a)])
#[<class 'str'>, <class 'str'>, <class 'str'>, <class 'int'>, <class 'str'>, <class 'str'>, <class 'float'>, <class 'str'>, <class 'str'>]

for i, word in enumerate(split_type):
    if type(word) == int:
        print('Integer found at position {:d}'.format(i + 1))
# Returns: 'Integer found at position 4'
Ma0
  • 15,057
  • 4
  • 35
  • 65
0

split() won't do this because it is specific to strings.

However you can post-process the output from split to check whether each element of its output could be cast to an integer or not, per this answer. Something like:

def maybeCoerceInt(s):
    try: 
        return int(s)
    except ValueError:
        return s

tokens = a.split()
for i in range(len(tokens)):
    tokens[i] = maybeCoerceInt(tokens[i])

Which produces

>>> print(tokens)
['Hello', 'I', 'have', 4, 'ducks']
Community
  • 1
  • 1
Jeff G
  • 908
  • 8
  • 18
0

you can use isdigit function

a='Hello I have 4 ducks'
i=0
for  x in a.split():
  i+=1
  if x.isdigit():
     print "Element:"+x
     print "Position:"+i
Danilo C
  • 5
  • 3
0

Probably using exception is the best way. (see here). Other methods like isdigit do not work with negative numbers.

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

Also note:

float('NaN')
nan

Then you could use:

if is_number(a[i]):
    punt=k
Community
  • 1
  • 1
DurgaDatta
  • 3,952
  • 4
  • 27
  • 34
0

You can use the eval function to do it, here is my anwser:

a = 'Hello I have 4 ducks weighing 3 kg each'
a = a.split()
print a

for i in a:
    try:
        if isinstance(eval(i), int):
            print "the index of {i} is {index}".format(i=i, index=a.index(i))
    except NameError:
        pass

# the results
['Hello', 'I', 'have', '4', 'ducks', 'weighing', '3', 'kg', 'each']
the index of 4 is 3
the index of 3 is 6