user2848250
user2848250

Reputation: 35

how to print string that has " . " in python

I am trying to print 23.45 and 7.8 by searching "." in each string. here is my code.

mylist = ["1,23.45,6,7.8","1,25,999"]

tokens =mylist[0].split(',')

for number in tokens :

if re.search('.', number) :

print number ,

outcome: 1 23.45 6 7.8

Upvotes: 0

Views: 43

Answers (2)

roippi
roippi

Reputation: 25974

As always, I advise people not to use regex when they don't need regex. In this case, use the in operator.

if '.' in number:

replaces

if re.search('.', number):

Which, if you're curious, should have been

if re.search('\.', number):

Upvotes: 2

Lucas Ribeiro
Lucas Ribeiro

Reputation: 6282

Try this. Regex doesn't look pythonic at all for me.

mylist = ["1,23.45,6,7.8","1,25,999"]
tokens =mylist[0].split(',')

for number in tokens :
    if "." in number:   
        print number

But my special favorite doesn't look much pythonic. But i learned to love lambdas over loops.

mylist = ["1,23.45,6,7.8","1,25,999"]
tokens =mylist[0].split(',')
result = filter(lambda x: "." in x, tokens)
print result

Upvotes: 1

Related Questions