I have a Django model, which is essentially a list of words. It is very simple and is defined as follows:
class Word(models.Model):
word = models.CharField(max_length=100)
I need the particular word as a string object. (I am replacing all the characters in the word with asterisks for a simple Hangman game.) However, I cannot seem to get the word as a string object.
I tried adding this method to the Word class, but that did not seem to work either.
def __str__(self):
return str(self.word)
I get an empty string object instead of the word.
What do I need to do to get the value of the CharField as a string object? Thanks for your help.
Edit: The weird thing for me is that it has no problem returning an integer. For example, if I were do do something like this:
word = Word(pk=2821)
print word.id
... it would print 2821, the id of that particular record.
Are you sure you're fetching the Word objects correctly? The line in your example word = Word(pk=2821) creates a new Word object with a pk of 2821 and a blank word field. If you've fetched an actual Word object from the database that has a value in its word field, then word.word should return a string. E.g.
>>>> w1 = Word(pk=5, word='eggs')
>>>> w1.word
'eggs'
>>>> w1.save()
>>>> w2 = Word.objects.get(pk=5)
>>>> w2.word
u'eggs'
Can you also verify that the words are being correctly stored in your database by connecting to it with a DB client and looking at the output of:
SELECT word FROM yourappname_word LIMIT 20;
Like I said, word.word should work, so the problem might lie in how you're saving or fetching your Word objects.
Related
I'm using sqlite3 and trying to get the oid by using the title of the row and then trying to use that oid to update a column in my table.
allOID is a tuple, and when I print it i get this:
>>> <class 'tuple'>
>>> [(1,)]
I'm trying to get the integer out of this tuple but the comma is throwing it off and I can't seem to get it.
Here is all of the code being used currently:
c.execute("""SELECT oid FROM books
WHERE title = :title""",
{
'title': title
})
allOID = c.fetchall()
print(type(allOID[0]))
print(allOID)
c.execute("SELECT * FROM books")
c.execute("""UPDATE books SET
rented = :rented
WHERE oid = :oid""",
{
'rented': rentedVar,
'oid': allOID[0]
})
any help and comments are greatly appreciated!
The comma just indicates that it is a tuple with a single element.
Access it using allOID[0][0].
allOID[0] gets you the tuple out of the list of results, going one level further with allOID[0][0] gets you the first element of the tuple.
For more info, see the docs:
Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective.
So I have to go through a bunch of code to get some data from an iframe. the iframe has a lot of data but in there is an object called '_name'. the first key of name is 'extension_id' and its value is a big long string. the json object is enclosed in apostrophes. I have tried removing the apostrophes but still instead of 'extension_id_output' I get a single curly bracket. the json object looks something like this
Frame {
...
...
_name: '{"extension_id":"a big huge string that I need"} "a bunch of other stuff":"this is a valid json object as confirmed by jsonlint", "globalOptions":{"crev":"1.2.50"}}}'
}
it's a whole big ugly paragraph but I really just need the extension_id. so this is the code I'm currently using after attempt 100 or whatever.
var frames = await page.frames();
// I'm using puppeteer for this part but I don't think that's relevant overall.
var thing = frames[1]._name;
console.log(frames[1])
// console.log(thing)
thing.replace(/'/g, '"')
// this is to remove the apostrophes from the outside of the object. I thought that would change things before. it does not. still outputs a single {
JSON.parse(thing)
console.log(thing[0])
instead of getting a big huge string that I need or whatever is written in extension_id. I get a {. that's it. I think that is because the whole object starts with a curly bracket. this is confirmed to me because console.log(thing[2]) prints e. so what's going on? jsonlint says this is a valid json object but maybe it's just a big string and I should be doing some kind of split to grab whaat's between the first : and the first ,. I'm really not sure.
For two reasons:
object[0] doesn't return the value an object's "first property", it returns the value of the property with the name "0", if any (there probably isn't in your object); and
Because it's JSON, and when you're dealing with JSON in JavaScript code, you are by definition dealing with a string. (More here.) If you want to deal with the object that the JSON describes, parse it.
Here's an example of parsing it and getting the value of the extension_id property from it:
const parsed = JSON.parse(frames[1]._name);
console.log(parsed.extension_id); // The ID
I want to return the index of my DataFrame as a string. I am using this commandp_h = peak_hour_df.index.astype(str).str.zfill(4) It is not working, I am getting this result: Index(['1645'], dtype='object', name I need it to return the string '1645' How do I accomplish this?
In short:
do p_h = list(peak_hour_df.index.astype(str).str.zfill(4)). This will return a list and then you can index it.
In more detail:
When you do peak_hour_df.index.astype(str), as you see, the dtype is already an object (string), so that job is done. Note this is the type of the contents; not of the object itself. Also I am removing .str.zfill(4) as this is additional and does not change the nature of the problem or the retuning type.
Then the type of the whole objet you are returning is pandas.core.indexes.base.Index. You can check this like so: type(peak_hour_df.index.astype(str)). If you want to return a single value from it in type str (e.g. the first value), then you can either index the pandas object directly like so:
peak_hour_df.index.astype(str)[0]
or (as I show above) you can covert to list and then index that list (for some reason, most people find it more intuitive):
peak_hour_df.index.astype(str).to_list()[0]
list(peak_hour_df.index.astype(str))[0]
I want to find a specific string within a string.
For example, let's say I have the string
string = "username:quantopia;password:blabla
How can I then find quantopia?
I am using python 3.
Update: I am sorry I did not mention what I try before..
string.split('username:',1)[1].split(';',1)[0]
But this look very bad and not efficient, I was hoping for something better.
Just use regex as such:
import re
username = re.search("username:(.*);password", "username:quantopia;password:blabla").group(1)
print("username:", username)
This will output quantopia.
In this expression "username:(.*);password" you are saying "give me everything from username: to ;password" So this is why you're getting quantopia. This might as well be ":(.*);" as it will output the same thing in this case.
The simple solution is:
string = "username:quantopia;password:blabla"
username = "username"
if username in string:
# do work.
You might be better to just use split to create a dictionary so you dont need to use multiple regex to extract different parts of data sets. The below will split stirng into key value pairs then split key value pairs then pass the list of lists to dict to create a dictionary.
string = "username:quantopia;password:blabla"
data = dict([pairs.split(':') for pairs in string.split(';')])
print(f'username is "{data["username"]}" and password is "{data["password"]}"')
OUTPUT
username is "quantopia" and password is "blabla"
I am using haystack with whoosh backend. And set up a EdgeNgramField. But when i search for word colored it includes the results for word one-colored too.
class TagIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True)
name = indexes.EdgeNgramField( model_attr='name')
name_tr = indexes.EdgeNgramField(model_attr='name_tr')
def get_model(self):
return Tag
I have tried adding double quotes but the results are the same.
How can i get exact matches. Do i need to write custom search query?