Python string operation - python

I want to get the following output:
"my_www.%first_game_start_time%("REN", "233_736")"
Would you please tell me what is wrong in code below:
u = "my_www.%%first_game_start_time%%(%s, %s)" %("REN", "233_736")
Best Regards

If you are asking how to embed " in the string, triple quotes is an easy way
u = """my_www.%%first_game_start_time%%("%s", "%s")"""%("REN", "233_736")
Another way is to escape the " with a \
u = "my_www.%%first_game_start_time%%(\"%s\", \"%s\")"%("REN", "233_736")
Since you have no ' in the string, you could also use those to delimit the string
u = 'my_www.%%first_game_start_time%%("%s", "%s"))'%("REN", "233_736")

Generally you need to post your expected output and point out the difference between that and the output you receive, or include an error message you are receiving, to get a usable answer. But, I suspect the problem is that you want the value of c to be inserted into the string u and instead the literal letter c is being inserted. If that is the case, the solution is:
c = "222"
u = "my_www.%%first_game_start_time%%(%s, %s, %s)" %("REN", "233_736", c)

I'm going to guess that you want this:
c = "222"
u = "my_www." + first_game_start_time("REN", "233_736", c)

Related

How can i make specific output using a strip function?

I am trying to remove some symbols from output, but it does not work. I've tried many ways to do this, also i searched many similar questions, but i still don't have an answer. Here is the code:
cur.execute("SELECT * FROM test;")
all = cur.fetchone()
str1 = str(all)
str2 = str1.strip("()")
str3 = str2.strip(",")
str4 = str3.strip("()")
str5 = str4.strip("''")
str6 = str5.strip("', '")
print(str6)
The output is:
f', 'f
Instead of:
f f
Sorry for bad code. Thanks for help
Maybe you are looking for .replace() function
string = "f', 'f"
string = string.replace("', '", " ")
print(string)
Outputs:
f f
Not entirely sure what you are asking. Strip pulls characters off of either side of the string if they exist. You may be looking for the .replace() method instead.
the strip()method only removes from left or right part of the string, not in the middle of the string. For that you would need to use replace()instead. Note that the way you seem to approach this wouldn't result in good code and isn't the way you would handle a db response.
I would rather recommend the following: The db call returns the result in a tuple datatype. In case you want to output the result from each individual item in the db call, i would rather recommend iterating through the result and converting each item to str rather than converting the entire result tuple to a string and replacing characters. The below would produce the output you are looking for and is a more correct way of going about it.
db_result = ('f', 'f')
for item in db_result:
print(str(item), end=" ")
print()

extract one element from the list with quotation mark

I would like to extract one element from list in python.
For example:
a = [0,1,2,3]
b = ['0','1','2','3']
a1 = a[0]
b1 = b[0]
print(a1)
print(b1)
As expected, the code print 0 for both a1 and b1.
However I would like to get '0' for both a1 and b1 with single quotation mark instead of 0.
Any idea or help would be really appreciate.
Thank you,
Issac
Quotation marks are not parts of a value - they are only for distinguish e. g. the number 1 from the string with the only symbol 1.
The print() function don't print quotation marks even around strings (unlike an interactive session when you give as input only a variable name or an expression).
So you have manually put them into the print() function, e. g.
print("'" + str(a1) + "'")
print("'" + b1 + "'")
or
print("'{}'".format(a1))
print("'{}'".format(b1))
or - in Python 3.6+ -
print(f"'{a1}'")
print(f"'{b1}'")
Normally, Python will print a string without quotes. That's standard in almost all programming languages.
However, Python does let you print a string with the quotes, you just need to tell it to print the representation of the string. One way to do that is with the !r formatting directive.
The items in a are integers, if you want them printed as strings you need to convert them to strings.
a = [0, 1, 2, 3]
b = ['0','1','2','3']
a1 = a[0]
b1 = b[0]
print('{!r}'.format(str(a1)))
print('{!r}'.format(b1))
output
'0'
'0'
You can read about the representation of a string in the official tutorial.
There are other ways to see the representation of a string. For example, you can call the built-in repr function:
print(repr(b1))
Bear in mind that if a string already contains single-quote chars then its representation will be enclosed in double-quotes:
s = "A 'test' string"
print(repr(s))
output
"A 'test' string"
And if the string contains a mixture of quotes then the representation will revert to using single quotes, and using backslash escapes to denote single quotes:
s = "A 'test' \"string\""
print(repr(s))
output
'A \'test\' "string"'
So if for some reason you don't want that behaviour, then you will need to print the quote marks explicitly:
s = "A 'test' string"
print("'{}'".format(s))
output
'A 'test' string'
well,
>>> print(repr(str(a1)))
'0'
>>> print(repr(str(b1)))
'0'
will do, but as commented by others I am unsure about your intentions.
I searched online and found Why are some Python strings are printed with quotes and some are printed without quotes?
I think if you print as follows, it will work as you wish:
print(repr(a1))
print(repr(b1))

How to replace user's input?

I'm trying to make a Text to Binary converter script. Here's what I've got..
userInput = input()
a = ('00000001')
b = ('00000010')
#...Here I have every remaining letter translated in binary.
z = ('00011010')
So let's say the user types the word "Tree", I want to convert every letter in binary and display it. I hope you can understand what I'm trying to do here.
PS. I'm a bit newbie! :)
The way you have attempted to solve the problem isn't ideal. You've backed yourself into a corner by assigning the binary values to variables.
With variables, you are going to have to use eval() to dynamically get their value:
result = ' '.join((eval(character)) for character in myString)
Be advised however, the general consensus regarding the use of eval() and similar functions is don't. A much better solution would be to use a dictionary to map the binary values, instead of using variables:
characters = { "a" : '00000001', "b" :'00000010' } #etc
result = ' '.join(characters[character] for character in myString)
The ideal solution however, would be to use the built-in ord() function:
result = ' '.join(format(ord(character), 'b') for character in myString)
Check the ord function:
userinput = input()
binaries = [ord(letter) for letter in userinput]
cheeky one-liner that prints each character on a new line with label
[print(val, "= ", format(ord(val), 'b')) for val in input()]
#this returns a list of "None" for each print statement
similarly cheeky one-liner to print with arbitrary seperator specified by print's sep value:
print(*[str(val) + "= "+str(format(ord(val), 'b')) for val in input()], sep = ' ')
Copy and paste into your favorite interpreter :)

Removing Quotation Marks from string in a list

Given a list :
q = ['"hello','it's','me']
I want to remove "'s" and the '"' at the beginning of hello to obtain:
q = ['hello','it','me']
I wrote:
for i in ['"s','"']:
q = [w.replace(i,'') for w in q]
This results in q=['"hello",'it','me']. The code does not seem to work for the quotation marks.
(I cannot comment because I don't have enought points so please excuse me for posting as an answer).
First your initial list q is not valid, the 'it's element will throw invalid syntax.
The easiest will be to sanitize your list elements before they're pushed, is this possible for you? For example, in the case of double quotes use
element = '"hello'
element.replace('"', '')
In the case of the single quote and the s:
element = "it's"
single_index = element.find("'")
new_element = element[0:single_index]
I hope this helps

Python - How to concatenate Strings and Integers in Python?

I'm with some trouble getting this code to work:
count_bicycleadcategory = 0
for item_bicycleadcategory in some_list_with_integers:
exec 'model_bicycleadcategory_%s.bicycleadcategorytype = BicycleAdCategoryType.objects.get(pk=' + str(item_bicycleadcategory) + ')' % count_bicycleadcategory
count_bicycleadcategory = count_bicycleadcategory + 1
I'm getting an error:
Type Error, not all arguments converted during string formatting
My question is: Any clue on how I pass the "item_bicycleadcategory" to the exec expression?
Best Regards,
You are already using python's format syntax:
"string: %s\ndecimal: %d\nfloat: %f" % ("hello", 123, 23.45)
More info here: http://docs.python.org/2/library/string.html#format-string-syntax
First, exec is even more dangerous than eval(), so be absolutely sure that your input is coming from a trusted source. Even then, you shouldn't do it. It looks like you're using a web framework or something of the sort, so really don't do it!
The problem is this:
exec 'model_bicycleadcategory_%s.bicycleadcategorytype = BicycleAdCategoryType.objects.get(pk=' + str(item_bicycleadcategory) + ')' % count_bicycleadcategory
Take a closer look. You're trying to put the string formatting argument to a single parentesis with no format strings with ')' % count_bicycleadcategory.
You could do this:
exec 'model_bicycleadcategory_%s.bicycleadcategorytype = BicycleAdCategoryType.objects.get(pk=' % count_bicycleadcategory + str(item_bicycleadcategory) + ')'
But what you really should be doing is not using exec at all!
Create a list of your model instances and use that instead.
for python 2.7 you could use format:
string = '{0} give me {1} beer'
string.format('Please', 3)
out:
Please give me 3 beer
you could do many things with format, for example:
string = '{0} give me {1} {0} beer'
out:
Please give me 3 Please beer.
try this :
exec 'model_bicycleadcategory_%s.bicycleadcategorytype = BicycleAdCategoryType.objects.get(pk=%s)' % (count_bicycleadcategory, str(item_bicycleadcategory))
(you mustn't mix %s and string + concatenation at the same time)
Try this:
exec 'model_bicycleadcategory_%d.bicycleadcategorytype = BicycleAdCategoryType.objects.get(pk=%d)' % (count_bicycleadcategory, item_bicycleadcategory)

Categories

Resources