I have a string "42 0" (for example) and need to get an array of the two integers. Can I do a .split on a space?
Use str.split():
>>> "42 0".split() # or .split(" ")
['42', '0']
Note that str.split(" ") is identical in this case, but would behave differently if there were more than one space in a row. As well, .split() splits on all whitespace, not just spaces.
Using map usually looks cleaner than using list comprehensions when you want to convert the items of iterables to built-ins like int, float, str, etc. In Python 2:
>>> map(int, "42 0".split())
[42, 0]
In Python 3, map will return a lazy object. You can get it into a list with list():
>>> map(int, "42 0".split())
<map object at 0x7f92e07f8940>
>>> list(map(int, "42 0".split()))
[42, 0]
text = "42 0"
nums = [int(n) for n in text.split()]
l = (int(x) for x in s.split())
If you are sure there are always two integers you could also do:
a,b = (int(x) for x in s.split())
or if you plan on modifying the array after
l = [int(x) for x in s.split()]
This should work:
[ int(x) for x in "40 1".split(" ") ]
Of course you can call split, but it will return strings, not integers. Do
>>> x, y = "42 0".split()
>>> [int(x), int(y)]
[42, 0]
or
[int(x) for x in "42 0".split()]
Other answers already show that you can use split() to get the values into a list. If you were asking about Python's arrays, here is one solution:
import array
s = '42 0'
a = array.array('i')
for n in s.split():
a.append(int(n))
Edit: A more concise solution:
import array
s = '42 0'
a = array.array('i', (int(t) for t in s.split()))
You can split and ensure the substring is a digit in a single line:
In [1]: [int(i) for i in '1 2 3a'.split() if i.isdigit()]
Out[1]: [1, 2]
Given: text = "42 0"
import re
numlist = re.findall('\d+',text)
print(numlist)
['42', '0']
Use numpy's fromstring:
import numpy as np
np.fromstring("42 0", dtype=int, sep=' ')
>>> array([42, 0])
Related
a = input()
a = list(a)
then
>>> hello 1 5
['h','e','l','l','o',' ','1',' ','5']
How can I get the output like
a = ['hello', 1, 5]
You can use split to split it into words, and then use isdigit and cast for any sub strings that are integers.
[int(x) if x.isdigit() else x for x in a.split()]
x = [1,2,3]
print '-'.join(str(x))
Expected:
1-2-3
Actual:
(-1-,- -2-,- -3-)
What is going on here?
Because calling str on the list in its entirety gives the entire list as a string:
>>> str([1,2,3])
'[1, 2, 3]'
What you need to do is cast each item in the string to an str, then do the join:
>>> '-'.join([str(i) for i in x])
'1-2-3'
You sent x to str() first, putting the given delimiter between each character of the string representation of that whole list. Don't do that. Send each individual item to str().
>>> x = [1,2,3]
>>> print '-'.join(map(str, x))
1-2-3
I'm trying to extract numbers from a string like "12+13".
When I extract only the numbers from it into a list it becomes [1,2,1,3]
actually I want the list to take the numbers as [12,13] and 12,13 should be integers also.
I have tried my level best to solve this,the following is the code
but it still has a disadvantage .
I am forced to put a space at the end of the string...for it's correct functioning.
My Code
def extract(string1):
l=len(string1)
pos=0
num=[]
continuity=0
for i in range(l):
if string[i].isdigit()==True:
continuity+=1
else:
num=num+ [int(string[pos:continuity])]
continuity+=1
pos=continuity
return num
string="1+134-15 "#added a spaces at the end of the string
num1=[]
num1=extract(string)
print num1
This will work perfectly with your situation (and with all operators, not just +):
>>> import re
>>> equation = "12+13"
>>> tmp = re.findall('\\b\\d+\\b', equation)
>>> [int(i) for i in tmp]
[12, 13]
But if you format your string to be with spaces between operators (which I think is the correct way to go, and still supports all operators, with a space) then you can do this without even using regex like this:
>>> equation = "12 + 13"
>>> [int(s) for s in equation.split() if s.isdigit()]
[12, 13]
Side note: If your only operator is the + one, you can avoid regex by doing:
>>> equation = "12+13"
>>> [int(s) for s in equation.split("+") if s.isdigit()]
[12, 13]
The other answer is great (as of now), but I want to provide you with a detailed explanation. What you are trying to do is split the string on the "+" symbol. In python, this can be done with str.split("+").
When that translates into your code, it turns out like this.
ourStr = "12+13"
ourStr = ourStr.split("+")
But, don't you want to convert those to integers? In python, we can use list comprehension with int() to achieve this result.
To convert the entire array to ints, we can use. This pretty much loops over each index, and converts the string to an integer.
str = [int(s) for s in ourStr]
Combining this together, we get
ourStr = "12+13"
ourStr = ourStr.split("+")
ourStr = [int(s) for s in ourStr]
But lets say their might be other unknown symbols in the array. Like #Idos used, it is probably a good idea to check to make sure it is a number before putting it in the array.
We can further refine the code to:
ourStr = "12+13"
ourStr = ourStr.split("+")
ourStr = [int(s) for s in ourStr if s.isdigit()]
This can be solved with just list comprehension or built-in methods, no need for regex:
s = '12+13+14+15+16'
l = [int(x) for x in s.split('+')]
l = map(int, s.split('+'))
l = list(map(int, s.split('+'))) #If Python3
[12, 13, 14, 15, 16]
If you are not sure whether there are any non-digit strings, then just add condition to the list comprehension:
l = [int(x) for x in s.split('+') if x.isdigit()]
l = map(lambda s:int(s) if s.isdigit() else None, s.split('+'))
l = list(map(lambda s:int(s) if s.isdigit() else None, s.split('+'))) #If python3
Now consider a case where you could have something like:
s = '12 + 13 + 14+15+16'
l = [int(x.strip()) for x in s.split('+') if x.strip().isdigit()]#had to strip x for any whitespace
l = (map(lambda s:int(s.strip()) if s.strip().isdigit() else None, s.split('+'))
l = list(map(lambda s:int(s.strip()) if s.strip().isdigit() else None, s.split('+'))) #Python3
[12, 13, 14, 15, 16]
Or:
l = [int(x) for x in map(str.strip,s.split('+')) if x.isdigit()]
l = map(lambda y:int(y) if y.isdigit() else None, map(str.strip,s.split('+')))
l = list(map(lambda y:int(y) if y.isdigit() else None, map(str.strip,s.split('+')))) #Python3
You can just use Regular Expressions, and this becomes very easy:
>>> s = "12+13"
>>> import re
>>> re.findall(r'\d+',s)
['12', '13']
basically, \d matches any digit and + means 1 or more. So re.findall(r'\d+',s) is looking for any part of the string that is 1 or more digits in a row and returns each instance it finds!
in order to turn them to integers, as many people have said, you can just use a list comprehension after you get the result:
result = ['12', '13']
int_list = [int(x) for x in result]
python regex documentation
I have made a function which extracts number from a string.
def extract(string1):
string1=string1+" "
#added a spaces at the end of the string so that last number is also extracted
l=len(string1)
pos=0
num=[]
continuity=0
for i in range(l):
if string1[i].isdigit()==True:
continuity+=1
else:
if pos!=continuity:
''' This condition prevents consecutive execution
of else part'''
num=num+ [int(string1[pos:continuity])]
continuity+=1
pos=continuity
return num
string="ab73t9+-*/182"
num1=[]
num1=extract(string)
print num1
I have a string "42 0" (for example) and need to get an array of the two integers. Can I do a .split on a space?
Use str.split():
>>> "42 0".split() # or .split(" ")
['42', '0']
Note that str.split(" ") is identical in this case, but would behave differently if there were more than one space in a row. As well, .split() splits on all whitespace, not just spaces.
Using map usually looks cleaner than using list comprehensions when you want to convert the items of iterables to built-ins like int, float, str, etc. In Python 2:
>>> map(int, "42 0".split())
[42, 0]
In Python 3, map will return a lazy object. You can get it into a list with list():
>>> map(int, "42 0".split())
<map object at 0x7f92e07f8940>
>>> list(map(int, "42 0".split()))
[42, 0]
text = "42 0"
nums = [int(n) for n in text.split()]
l = (int(x) for x in s.split())
If you are sure there are always two integers you could also do:
a,b = (int(x) for x in s.split())
or if you plan on modifying the array after
l = [int(x) for x in s.split()]
This should work:
[ int(x) for x in "40 1".split(" ") ]
Of course you can call split, but it will return strings, not integers. Do
>>> x, y = "42 0".split()
>>> [int(x), int(y)]
[42, 0]
or
[int(x) for x in "42 0".split()]
Other answers already show that you can use split() to get the values into a list. If you were asking about Python's arrays, here is one solution:
import array
s = '42 0'
a = array.array('i')
for n in s.split():
a.append(int(n))
Edit: A more concise solution:
import array
s = '42 0'
a = array.array('i', (int(t) for t in s.split()))
You can split and ensure the substring is a digit in a single line:
In [1]: [int(i) for i in '1 2 3a'.split() if i.isdigit()]
Out[1]: [1, 2]
Given: text = "42 0"
import re
numlist = re.findall('\d+',text)
print(numlist)
['42', '0']
Use numpy's fromstring:
import numpy as np
np.fromstring("42 0", dtype=int, sep=' ')
>>> array([42, 0])
Suppose I had a string
string1 = "498results should get"
Now I need to get only integer values from the string like 498. Here I don't want to use list slicing because the integer values may increase like these examples:
string2 = "49867results should get"
string3 = "497543results should get"
So I want to get only integer values out from the string exactly in the same order. I mean like 498,49867,497543 from string1,string2,string3 respectively.
Can anyone let me know how to do this in a one or two lines?
>>> import re
>>> string1 = "498results should get"
>>> int(re.search(r'\d+', string1).group())
498
If there are multiple integers in the string:
>>> map(int, re.findall(r'\d+', string1))
[498]
An answer taken from ChristopheD here: https://stackoverflow.com/a/2500023/1225603
r = "456results string789"
s = ''.join(x for x in r if x.isdigit())
print int(s)
456789
Here's your one-liner, without using any regular expressions, which can get expensive at times:
>>> ''.join(filter(str.isdigit, "1234GAgade5312djdl0"))
returns:
'123453120'
if you have multiple sets of numbers then this is another option
>>> import re
>>> print(re.findall('\d+', 'xyz123abc456def789'))
['123', '456', '789']
its no good for floating point number strings though.
Iterator version
>>> import re
>>> string1 = "498results should get"
>>> [int(x.group()) for x in re.finditer(r'\d+', string1)]
[498]
>>> import itertools
>>> int(''.join(itertools.takewhile(lambda s: s.isdigit(), string1)))
With python 3.6, these two lines return a list (may be empty)
>>[int(x) for x in re.findall('\d+', your_string)]
Similar to
>>list(map(int, re.findall('\d+', your_string))
this approach uses list comprehension, just pass the string as argument to the function and it will return a list of integers in that string.
def getIntegers(string):
numbers = [int(x) for x in string.split() if x.isnumeric()]
return numbers
Like this
print(getIntegers('this text contains some numbers like 3 5 and 7'))
Output
[3, 5, 7]
def function(string):
final = ''
for i in string:
try:
final += str(int(i))
except ValueError:
return int(final)
print(function("4983results should get"))
Another option is to remove the trailing the letters using rstrip and string.ascii_lowercase (to get the letters):
import string
out = [int(s.replace(' ','').rstrip(string.ascii_lowercase)) for s in strings]
Output:
[498, 49867, 497543]
integerstring=""
string1 = "498results should get"
for i in string1:
if i.isdigit()==True
integerstring=integerstring+i
print(integerstring)