I am getting an error here and I am wondering if any of you can see where I went wrong. I am pretty much a beginner in python and can not see where I went wrong.
temp = int(temp)^2/key
for i in range(0, len(str(temp))):
final = final + chr(int(temp[i]))
"temp" is made up of numbers. "key" is also made of numbers. Any help here?
First, you defined temp as an integer (also, in Python, ^ isn't the "power" symbol. You're probably looking for **):
temp = int(temp)^2/key
But then you treated it as a string:
chr(int(temp[i]))
^^^^^^^
Was there another string named temp? Or are you looking to extract the ith digit, which can be done like so:
str(temp)[i]
final = final + chr(int(temp[i]))
On that line temp is still a number, so use str(temp)[i]
EDIT
>>> temp = 100 #number
>>> str(temp)[0] #convert temp to string and access i-th element
'1'
>>> int(str(temp)[0]) #convert character to int
1
>>> chr(int(str(temp)[0]))
'\x01'
>>>
Related
VERSION = ["'pilot-2'", "'pilot-1'"]
VERSIONS_F = []
for item in VERSION:
temp = item.replace('"','')
VERSIONS_F.append(temp)
print (VERSIONS_F)
In the above block of code VERSIONS_F is also printing the same ["'pilot-2'", "'pilot-1'"], but I would need something like ['pilot-2', 'pilot-1']. I even tried strip('"') and am not seeing what I want.
You can do this in a couple of lines:
VERSION = ["'pilot-2'", "'pilot-1'"]
VERSIONS_F = [item [1:-1] for item in VERSION]
print(VERSIONS_F)
OUTPUT:
['pilot-2', 'pilot-1']
This way simply slices the first and last character from the string, which assumes that the "" are always at the first and last position.
Note: Grismar gives a good overview of what is happening under the hood as well
Try this:
VERSION = ["'pilot-2'", "'pilot-1'"]
VERSIONS_F = []
for item in VERSION:
temp = item.replace("'",'')
VERSIONS_F.append(temp)
print (VERSIONS_F)
it will print ['pilot-2','pilot-1']
When you print a list, Python will print the representation of the list, so the strings inside of the list are not printed like a string normally is:
>>> print('hello')
hello
Compared to:
>>> print(['hello'])
['hello']
Adding different quotes will cause Python to select the opposite quotes to represent the string:
>>> print(['\'hello\''])
["'hello'"]
>>> print(["\"hello\""])
['"hello"']
Beginning Python programmers often make the mistake of confusing what is printed on the console with an actual value. print(x) doesn't show you the actual value of x (whatever that may be), but its text string representation.
For example:
>>> x = 0xFF
>>> print(x)
255
Here, a value is assigned as its hexadecimal representation, but of course the actual value is just 255 (in decimal representation) and the decimal representation is the standard representation chosen when printing an integer value.
The 'real' value of the variable is an abstract numerical value, choices made when representing it don't affect that.
In your case, you defined the strings as having single quotes as part of the string using VERSION = ["'pilot-2'", "'pilot-1'"]. So, if you want to remove those single quotes, you could:
VERSION = ["'pilot-2'", "'pilot-1'"]
VERSIONS_F = []
for item in VERSION:
temp = item.replace("'",'')
VERSIONS_F.append(temp)
print (VERSIONS_F)
Result:
['pilot-2']
['pilot-2', 'pilot-1']
Or, more simply:
VERSIONS_F = [v.strip("'") for v in VERSION]
In response to the comment:
VERSION = ["'pilot-2'", "'pilot-1'"]
temp_list = ['pilot-1', 'test-3']
print(any(x in [v.strip("'") for v in VERSION] for x in temp_list))
I am currently working with JSON and Python and I have a problem.
When I write:
x = {}
x['red'] = {'name': "red"}
y = {}
y['red'] = {'p': 1}
z = x['red']['name'], y['red']['p']
print(z)
I get back:
('red', 1)
But I want it like:
red1
Without using
print(x['red']['name'], y['red']['p'])
Thanks for your help :)
When we resolve the variables in the line
z = x['red']['name'], y['red']['p']
we get this:
z = "red", 1
This is, in Python the same as writing:
z = ("red", 1)
This line defines a data-type called a "tuple". It is similar to a list. When you use print to write out the value of this variable, Python formats this as such and adds the parens.
If you want the string "red1" as output, you need to do some minor string processing. In your tuple, your first item is a string, the next is an integer. Those two are not directly concatenable in Python using +. You either need to convert (cast) the number first, or use a string formatting function:
Example 1 - Using str() to cast the number to string
z = x['red']['name'] + str(y['red']['p'])
Example 2 - Using simple string formatting
z = '%s%s' % (x['red']['name'], y['red']['p'])
Example 3 - Using f-strings
z = f"{x['red']['name']}{y['red']['p']}"
Just concatenate the string, easy:
z = y['red']['name'] + str(z['red']['p'])
print(z)
You need to call str() around z['red']['p'] because it's an integer. By converting it to a string, you can then concatenate the two strings into one string
When you type z = x['red']['name'], y['red']['p'] Python automatically takes it as tuple.
But you want this to be treated as string and get concatenated results.
for this you may use,
z = str(x['red']['name']) + str(y['red']['p'])
print(''.join(z)) does the trick.
Cheers
Demo: https://repl.it/repls/MinorRoyalTrace
Edit: use print(''.join(str(element) for element in z)) instead for handle str+ int
I am trying to loop through elements on the page and then get the text from the element. While getting the text, I am trying to strip a specific word "NEW" and then add it in the list.
Here is my code.
def test(self, cardname):
mylist = []
allrows = self.driver.find_elements_by_xpath("//*[contains(#id, 'scopes-pending-')]")
count = len(allrows)
for i in range(count):
rows = self.driver.find_element_by_id("scopes-" + cardname + "" + str(i) + "").text
if "NEW" in rows:
row_split = rows.strip('NEW')
mylist.append(row_split.text)
else:
mylist.append(rows.text)
return mylist
But I am getting this error
Exception: 'str' object has no attribute 'text'
I have tried a bunch of different ways but none of them are working. For example,
rows = self.driver.find_element_by_id("scopes-" + cardname + "" + i + "").text
which gives me the following error:
Exception: must be str, not int
It seems like I am missing something very small and need help figuring it out (still new to python). Any help is appreciated.
One thing you want to get right from the very beginning is to use descriptive variable names. This will help you and anyone else that has to read your code understand what you are trying to do.
I changed a few variable names using my best guess at what they were. Obviously feel free to change them to whatever makes sense if I guessed wrong.
mylist -> labelList
allrows -> rowLabels
rows -> rowLabel (singular since it's only one)
Removed some "extra" variables. I tend to not create a new variable if I'm not going to use it again. For example, count just holds len(allrows). You can remove count and just use len(allrows) in the only place it shows up, in the for loop.
Removed some extra ""s you had in your locator, e.g. ...cardname + "" + str(i) + "". The + "" + doesn't do anything here since you are just concatenating an empty string "" so I removed those.
rows.strip() will remove the string if the substring exists. If the substring doesn't exist, it just returns the entire string. Since this is the case, you don't need an if-else.
The below code is how I would write this.
def test(self, cardname):
labelList = []
allrows = self.driver.find_elements_by_xpath("//*[contains(#id, 'scopes-pending-')]")
for i in range(len(allrows)):
rowLabel = self.driver.find_element_by_id("scopes-" + cardname + str(i)).text
labelList.append(rowLabel.strip('NEW'))
return labelList
Caveat... I'm not a python programmer so there may be some more optimizations and ways to make this code more python-y than I have suggested.
As to the errors,
Exception: 'str' object has no attribute 'text'
row_split = rows.strip('NEW')
mylist.append(row_split.text)
In the above lines, row_split is a string and you are doing <string>.text which causes the error. .text can be used on a Web Element.
Exception: must be str, not int
rows = self.driver.find_element_by_id("scopes-" + cardname + "" + i + "").text
You fixed this one already. It's complaining that i is an int and not a string. str(i) fixes that.
Have you tried just appending row_split? If it's a str object, it likely is the text you're looking for (str in Python is the string object).
If you added the line you're getting the error on, that'd be helpful too.
My guess is that your first exception is from trying to get the text attribute from row_split from a string (I assume that the the text attribute returned from self.driver.find_element_by_id is of type str).
And then you get the second exception from trying to concatenate a str and an int (that'd be i). You were right to cast i to a str.
So this is what I'm trying to do:
input: ABCDEFG
Desired output:
***DEFG
A***EFG
AB***FG
ABC***G
ABCD***
and this is the code I wrote:
def loop(input):
output = input
for index in range(0, len(input)-3): #column length
output[index:index +2] = '***'
output[:index] = input[:index]
output[index+4:] = input[index+4:]
print output + '\n'
But I get the error: TypeError: 'str' object does not support item assignment
You cannot modify the contents of a string, you can only create a new string with the changes. So instead of the function above you'd want something like this
def loop(input):
for index in range(0, len(input)-3): #column length
output = input[:index] + '***' + input[index+4:]
print output
Strings are immutable. You can not change the characters in a string, but have to create a new string. If you want to use item assignment, you can transform it into a list, manipulate the list, then join it back to a string.
def loop(s):
for index in range(0, len(s) - 2):
output = list(s) # create list from string
output[index:index+3] = list('***') # replace sublist
print(''.join(output)) # join list to string and print
Or, just create a new string from slices of the old string combined with '***':
output = s[:index] + "***" + s[index+3:] # create new string directly
print(output) # print string
Also note that there seemed to be a few off-by-one errors in your code, and you should not use input as a variable name, as it shadows the builtin function of the same name.
In Python, strings are immutable - once they're created they can't be changed. That means that unlike a list you cannot assign to an index to change the string.
string = "Hello World"
string[0] # => "H" - getting is OK
string[0] = "J" # !!! ERROR !!! Can't assign to the string
In your case, I would make output a list: output = list(input) and then turn it back into a string when you're finished: return "".join(output)
In python you can't assign values to specific indexes in a string array, you instead will probably want to you concatenation. Something like:
for index in range(0, len(input)-3):
output = input[:index]
output += "***"
output += input[index+4:]
You're going to want to watch the bounds though. Right now at the end of the loop index+4 will be too large and cause an error.
strings are immutable so don't support assignment like a list, you could use str.join concatenating slices of your string together creating a new string each iteration:
def loop(inp):
return "\n".join([inp[:i]+"***"+inp[i+3:] for i in range(len(inp)-2)])
inp[:i] will get the first slice which for the first iteration will be an empty string then moving another character across your string each iteration, the inp[i+3:] will get a slice starting from the current index i plus three indexes over also moving across the string one char at a time, you then just need to concat both slices to your *** string.
In [3]: print(loop("ABCDEFG"))
***DEFG
A***EFG
AB***FG
ABC***G
ABCD***
I need to declare certain values in List.
Values looks like this:
["compute","controller"], ["compute"] ,["controller"]
I know the List syntax in python is
example = []
I am not sure how I will include square brackets and double quotes in the List.
Could anyone please help.
I tried the following:
cls.node = ["\["compute"\]","\["controller"\]"]
cls.node = ["[\"compute\"]","[\"controller\"]"]
Both did not work.
I think you mean list not dictionary because that is the syntax of a list:
You can simply do it using the following format '"Hello"':
cls.node = ['["compute"]','["controller"]']
cls.node = ['["compute"]','["controller"]']
Demo:
s = ['["hello"]', '["world"]']
for i in s:
print i
[OUTPUT]
["hello"]
["world"]