Reputation: 109
In one of my forms i send two bits of information like this:
<input type ="hidden" name= "items" value="{{item.pk}} {{item.name}}">
when I get the information with request.POST.get, I get "202 book".
How can I seperate just the number from the string or just the word? I did a split:
pks = request.POST.getlist("items")
for pk in pks:
pk.split(' ',1)
but the number isn't always a 1 or 2 digit number, it may be 2 or 3 etc. Also I might have the situations where the name is book1 so I would need that last "1" to remain.
Any ideas how I may go about this?
Upvotes: 1
Views: 91
Reputation: 78750
Unless I'm misinterpreting your question, why don't you just split the string and extract the first and second element from the resulting list? Demo:
>>> mystr = "202 book"
>>> lst = "202 book".split()
>>> num = lst[0] # or int(lst[0])
>>> num
'202'
>>> other = lst[1]
>>> other
'book'
If you have a string which contains numbers and words which could contain a number, but should not count when looking for numbers, you can do:
>>> mystr = 'This 101 5is 4 600a 42 de3mo string12'
>>> re.findall(r'\b\d+\b', mystr)
['101', '4', '42']
>>> re.findall(r'(?!\d+\b)\w+', mystr)
['This', '5is', '600a', 'de3mo', 'string12']
Upvotes: 2
Reputation: 599778
You have some useful answers on how to split up the data, but since you seem to be controlling both the template and the view, why are you putting them in the same field to begin with? Why not put them in two separate fields?
<input type="hidden" name="item_pk" value="{{item.pk}}">
<input type="hidden" name="item_name" value="{{item.name}}">
Upvotes: 1
Reputation: 107337
you can use this surely it work !
my_digit = ''.join(temp for temp in my_string if temp.isdigit())
or if you want to have the value of digit you can use int(my_digit)
Upvotes: 1
Reputation: 450
I have never used django, but how about using regular expressions?
import re
pk = "202 book";
print re.findall(r'\d\d?\d?',pk)
Upvotes: 0