I want to extract an integer value from string with no spaces between string and integer. The input is in the form 'n12' , 'n46' etc and the output should be like 12 and 46 respectively.
CodePudding user response:
Write loop that takes only digits from string, and then convert it to integer.
def convert_str(ns):
result = 0
for c in ns:
if c.isdigit():
result *= 10
result = int(c)
return result
CodePudding user response:
You could do something like this, though I am not sure if it is ideal or not
nums = ['0','1','2','3','4','5','6','7','8','9']
s = 'n42'
r = [i for i in s if i in nums]
r = int(''.join(r))
print(r)
CodePudding user response:
You can just used .replace:
x = 'n12'
x = int(x.replace('n',''))
x
And yes if you have a list you can used a loop with this fonction.
CodePudding user response:
Using regex module you can achieve this
import re
input_str = "n12 n46" # you can use 'n12' as well
temp = re.findall(r'\d ', input_str)
res = list(map(int, temp))
print("The numbers list is : " str(res))
# Output : The numbers list is : [12, 46]
CodePudding user response:
This is trivial with re.sub
.
import re
s = 'n46'
modified = re.sub(r'[^\d]', '', s)
We're substituting anything that isn't ([^ ]
) a digit (\d
) with nothing.