How to remove double quotes from list of strings? - python

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))

Related

Bytes Command Function Not Working for PySerial

I have a function which takes a set of values and converts it into a bytes string. For example, I need:
input_array = ['E9', '01','06','57','4A','01','F4','01','01','EF']
## needs to become b'\xE9\x01\x06\x57\x4A\x01\xF4\x01\x01\xEF'
The function I have is:
def string_to_command(inp):
new_string = ''
for i in inp:
new_string += r'\x' + i
return new_string.encode('latin-1')
When I print both commands:
print(string_to_command(input_array))
print(b'\xE9\x01\x06\x57\x4A\x01\xF4\x01\x01\xEF')
# OUTPUT b'\\xE9\\x01\\x06\\x57\\x4A\\x01\\xF4\\x01\\x01\\xEF'
# OUTPUT b'\xe9\x01\x06WJ\x01\xf4\x01\x01\xef'
I am not sure what is going on here. The last one with b"" actually commands my output device properly, the other does not. How do I fix this problem?
You can convert to int first, then to bytes.
>>> a = ['E9', '01','06','57','4A','01','F4','01','01','EF']
>>> bytes(int(x, base=16) for x in a)
b'\xe9\x01\x06WJ\x01\xf4\x01\x01\xef'
The last one with b"" actually commands my output device properly, the other does not. How do I fix this problem?
I think what is going on here is that you are trying to add \x to every value and then encoding it from there. The problem with that is 'E9' and \x'E9' are not the same:
>>> 'E9'.encode()
b'E9'
>>> '\xE9'.encode()
b'\xc3\xa9' <-- Not the same
>>>
One method I like is bytes.fromhex(s), where s is your 'hex string'.
input_array = ['E9', '01','06','57','4A','01','F4','01','01','EF']
# use "".join(input_array) to get all values combined
# into one string
res = bytes.fromhex( "".join(input_array) )
Outputs :
b'\xe9\x01\x06WJ\x01\xf4\x01\x01\xef'
You can join a list of bytes converted from the original array with latin-1 encoding. So adding \x as join sequence, it will output the desired bytes object:
input_array = ['E9', '01','06','57','4A','01','F4','01','01','EF']
print(b''.join([bytes.fromhex(x) for x in input_array]))
Output:
b'\xe9\x01\x06WJ\x01\xf4\x01\x01\xef'

Find a specific type of URL when 'n' URLs are provided

This will be my sample data:
lis = ['http://wiki.dbpedia.org/about','http://dbpedia.org/data/Category:Cybercrime.rdf',
'http://dbpedia.org/resource/Stop_Cyberbullying_Day',
'http://dbpedia.org/resource/Category:Cybercrime_in_Canada',
'http://dbpedia.org/resource/Political_repression_of_cyber-dissidents',
'http://creativecommons.org/licenses/by-sa/3.0/']
I have used the following code to filter only those URLs that contain http://dbpedia.org/resource/
c = 'http://dbpedia.org/resource/'
for i in lis:
if i[:27] is c:
print (i)
The expected output should be:
http://dbpedia.org/resource/Stop_Cyberbullying_Day
http://dbpedia.org/resource/Category:Cybercrime_in_Canada
http://dbpedia.org/resource/Political_repression_of_cyber-dissidents'
But prints NULL
There are two issues in your code:
You're using is for comparison, which compares the identity of two objects, not the equality. You want to use == instead.
Your string ('http://dbpedia.org/resource/') is 28 characters long, but you're comparing it to the first 26 characters of i. Replace your i[:27] with i[:29], or better yet use use i[:len(c)] to have it dynamically change with the c string.
All this being said, you should use str.startswith() which essentially does all of this for you:
for i in lis:
if i.starswith(c):
print(i)
is operator checks for identity of its operands.
Just use str.startwith for your simple case:
lst = ['http://wiki.dbpedia.org/about','http://dbpedia.org/data/Category:Cybercrime.rdf',
'http://dbpedia.org/resource/Stop_Cyberbullying_Day',
'http://dbpedia.org/resource/Category:Cybercrime_in_Canada',
'http://dbpedia.org/resource/Political_repression_of_cyber-dissidents',
'http://creativecommons.org/licenses/by-sa/3.0/']
c = 'http://dbpedia.org/resource/'
for url in lst:
if url.startswith(c):
print(url)
The output:
http://dbpedia.org/resource/Stop_Cyberbullying_Day
http://dbpedia.org/resource/Category:Cybercrime_in_Canada
http://dbpedia.org/resource/Political_repression_of_cyber-dissidents

Python Lists -Syntax for '['

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"]

String operations not working on python strings

I am using xlrd to read xls cell into a string, after which none of the string functions work on that string.
attribute_name = str(worksheet.cell_value(row,col))
attribute_name.strip()
attribute_name.lower()
print len(attribute_name)
if(len(attribute_name) > 8):
print 'value' + str(ord(attribute_name[8]))
print 'attributename:'+attribute_name+':'
prints :
9
value32
attributename:TSA01_HE :
9
value32
attributename:TSA02_HE :
I am mainly interested in getting rid of the whitespace at the end of the attribute name. Am I missing anything obvious ? I have tried replace etc but as you can see, even .lower() doesnt work.
$ python --version
Python 2.7.5
strip and lower do not work in place; they return the changed value. So you should assign their result to the old variable.
attribute_name = attribute_name.strip().lower()
Methods like str.XXX always return new strings instead of edit the original string. This is because strings are immutables in python. Likewise, operators on string like += rebinds the variable to a new string as well:
In [755]: s='a'
In [756]: id(s)
Out[756]: 30887376
In [757]: s+='bc' #same as s=s+'bc'
In [758]: id(s) #identity of the variable has been changed
Out[758]: 301145192
So if you wish your operation on a string to take effect, always remember to assign the result back with =.
Other immutables like ints, floats, tuples, frozensets works the same as strs. E.g., you won't expect i=3; i.__add__(10) makes i==13.
Take care that both strip() and lower() do not modify the string you apply them on; you should therefore do attribute_name = attribute_name.strip().lower().
Example:
>>> a = ' A '
>>> a.strip().lower()
'a'
>>> a
' A '

Python: 'int' object is not subscriptable

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'
>>>

Categories