How to convert a string looking like a list to list of floats? - python-3.x

I have this list:
s = '[ 0.00889175 -0.04808848 0.06218296 0.06312469 -0.00700571\n -0.08287739]'
it contains a '\n' character, I want to convert it to a list of float like this:
l = [0.00889175, -0.04808848, 0.06218296, 0.06312469, -0.00700571, -0.08287739]
I tried this code, which is close to what I want:
l = [x.replace('\n','').strip(' []') for x in s.split(',')]
but it still keeps quotes that I didn't manage to remove (i tried str.replace("'","") but it didn't work), this is what I get:
['0.00889175 -0.04808848 0.06218296 0.06312469 -0.00700571 -0.08287739']

You were quite close. This will work:
s = '[ 0.00889175 -0.04808848 0.06218296 0.06312469 -0.00700571\n -0.08287739]'
l = [float(n) for n in s.strip("[]").split()]
print(l)
Output:
[0.00889175, -0.04808848, 0.06218296, 0.06312469, -0.00700571, -0.08287739]

First thing needs to cleared that if you are keeping the str then there will be quotes unless you typecast each of element of your str by splitting it.
Following is my solution to your problem:
s='[ 0.00889175 -0.04808848 0.06218296 0.06312469 -0.00700571\n -0.08287739]'
#removing newline \n
new_str = s.replace('\n', '')
#stripping the brackets and extra space
new_str = new_str.strip(' []')
#splitting elements into a list
list_of_floats = new_str.split()
#typecasting from str to float
for _i, element in enumerate(list_of_floats):
list_of_floats[_i] = float(element)
print(list_of_floats)
#output
#[0.00889175, -0.04808848, 0.06218296, 0.06312469, -0.00700571, -0.08287739]

Related

Inserting values into strings in Python

I am trying to iterate over some integer values and insert them into an string which has to be in a weird format to work. The exact output (including the outer quotes) I need if the value was 64015 would be:
"param={\"zip\":\"64015\"}"
I have tried f string formatting but couldn't get it to work. It has problem with the backslashes and when I escaped them the output was not exactly like above string
Hopefully, I made myself clear enough.
You would have to escape the backslash and the double quotes seperately like this:
string = '"param={\\\"zip\\\":\\\"' + str(64015) + '\\\"}"'
The result of this is:
"param={\"zip\":\"64015\"}"
You can use alternate ways to delimit the outer string ('...', '''...''', """...""") or use str.format() or old style %-formatting syntax to get there (see f-style workaround at the end):
s = s = 'param={"zip":"' + str(64015) + '"}'
print(s)
s = '''param={"zip":"''' + str(64015) +'''"}'''
print(s)
s = """param={"zip":"64015"}""" # not suited for variable replacement
print(s)
s = 'param={{"zip":"{0}"}}'.format(64015)
print(s)
s = 'param={"zip":"%s"}' % 64015
print(s)
Output:
param={"zip":"64015"}
param={"zip":"64015"}
param={"zip":"64015"}
param={"zip":"64015"}
If you need any "\" in there simply drop a \\ in:
s = '"param={\\"zip\\":\\"' + str(64015) + '\\"}"'
print(s)
s = '''"param={\\"zip\\":\\"''' + str(64015) +'''\\"}"'''
print(s)
s = '"param={{\\"zip\\":\\"{0}\\"}}"'.format(64015)
print(s)
s = '"param={\\"zip\\":\\"%s\\"}"' % 64015
print(s)
Output:
"param={\"zip\":\"64015\"}"
"param={\"zip\":\"64015\"}"
"param={\"zip\":\"64015\"}"
"param={\"zip\":\"64015\"}"
The f-string workaround variant would look like so:
a = '\\"'
num = 64015
s = f'"param={{{a}zip{a}:{a}{num}{a}}}"'
and if printed also yields :
"param={\"zip\":\"64015\"}"
More on the topic can be found here: 'Custom string formatting' on python.org
I played around a bit with f-strings and .format() but ultimately got this to work:
foo = 90210
bar = '"param={\\"zip\\":\\"%s\\"}"' % (foo)
print(bar)
giving:
"param={\"zip\":\"90210\"}"
Hopefully someone can give you an f-string alternative. I kept running into unallowed "\" in my f-string attempts.
Is it only this?
a = "param={\"zip\":\"64015\"}"
b = a.split('=')
c = eval(b[1])
print(c)
print(c['zip'])
Result:
{'zip': '64015'}
64015
Please note that evaluating (eval()) strings from unknown source may
be dangerous! It may run the code that you are not expecting.

Create a list of strings with one/multiple character replacement

How to create a whole list of string from one string where each string in the list containing exactly one character replacement? The string itself is consisted of only four characters (say: A, B, C, and D), so that the whole list of a string of length n would contain 3n+1 strings with exactly one character replacement.
Example:
inputstr = 'ABCD'
output = ['ABCD', 'BBCD', 'CBCD', 'DBCD', 'AACD', 'ACCD', 'ADCD', 'ABAD', 'ABBD', 'ABDD', 'ABCA', 'ABCB', 'ABCC']
I write the following python code:
strin = 'ABCD'
strout = set()
tempstr1 = ''
tempstr2 = ''
tempstr3 = ''
tempstr4 = ''
for base in range(len(strin)):
if strin[base] == 'A': #this block will be repeated for char B, C and D
tempstr1 = strin.replace(strin[base], 'A')
strout.add(tempstr1)
tempstr1 = ''
tempstr2 = strin.replace(strin[base], 'B')
strout.add(tempstr2)
tempstr2 = ''
tempstr3 = strin.replace(strin[base], 'C')
strout.add(tempseq3)
tempstr3 = ''
tempstr4 = strin.replace(strin[base], 'D')
strout.add(tempseq4)
tempstr4 = ''
return strout
and it works well as long as there is no repeated character (such as 'ABCD'). However, when the input string contains repeated character (such as 'AACD'), it will return less than 3n+1 string. I tried with 'AACD' string and it returns only 10 instead of 13 strings.
Anyone can help?
change
strout = set() ===> strout = list()
I found it. I used a slicing method to create a list of total combination of strings with one replacement.
for i in range(len(seq)):
seqxlist.append(seq[:i] + 'x' + seq[i+1:])
and after that I filter out all the x-replaced strings which are longer than the original string length:
seqxlist = [x for x in seqxlist if (len(x) == len(seq))]
Then, I changed x into any of the substitution characters:
for m in seqxlist:
tempseq1 = m.replace('x', 'A')
outseq.append(tempseq1)
tempseq2 = m.replace('x', 'B')
outseq.append(tempseq2)
tempseq3 = m.replace('x', 'C')
outseq.append(tempseq3)
tempseq4 = m.replace('x', 'D')
outseq.append(tempseq4)
This will create all the possible combinations of string replacement, but still contains duplicates. To remove duplicates, I use set() to the outseq list.

Replace slice of string python with string of different size, but maintain structure

so today I was working on a function that removes any quoted strings from a chunk of data, and replaces them with format areas instead ({0}, {1}, etc...).
I ran into a problem, because the output was becoming completely scrambled, as in a {1} was going in a seemingly random place.
I later found out that this was a problem because the replacement of slices in the list changed the list so that it's length was different, and so the previous re matches would not line up (it only worked for the first iteration).
the gathering of the strings worked perfectly, as expected, as this is most certainly not a problem with re.
I've read about mutable sequences, and a bunch of other things as well, but was not able to find anything on this.
what I think i need is something like str.replace but can take slices, instead of a substring.
here is my code:
import re
def rm_strings_from_data(data):
regex = re.compile(r'"(.*?)"')
s = regex.finditer(data)
list_data = list(data)
val = 0
strings = []
for i in s:
string = i.group()
start, end = i.span()
strings.append(string)
list_data[start:end] = '{%d}' % val
val += 1
print(strings, ''.join(list_data), sep='\n\n')
if __name__ == '__main__':
rm_strings_from_data('[hi="hello!" thing="a thing!" other="other thing"]')
i get:
['"hello!"', '"a thing!"', '"other thing"']
[hi={0} thing="a th{1}r="other thing{2}
I would like the output:
['"hello!"', '"a thing!"', '"other thing"']
[hi={0} thing={1} other={2}]
any help would be appreciated. thanks for your time :)
Why not match both key=value parts using regex capture groups like this: (\w+?)=(".*?")
Then it becomes very easy to assemble the lists as needed.
Sample Code:
import re
def rm_strings_from_data(data):
regex = re.compile(r'(\w+?)=(".*?")')
matches = regex.finditer(data)
strings = []
list_data = []
for matchNum, match in enumerate(matches):
matchNum = matchNum + 1
strings.append(match.group(2))
list_data.append((match.group(1) + '={' + str(matchNum) + '} '))
print(strings, '[' + ''.join(list_data) + ']', sep='\n\n')
if __name__ == '__main__':
rm_strings_from_data('[hi="hello!" thing="a thing!" other="other thing"]')

How can I delete the letter that occurs in the two strings using python?

That's the source code:
def revers_e(str_one,str_two):
for i in range(len(str_one)):
for j in range(len(str_two)):
if str_one[i] == str_two[j]:
str_one = (str_one - str_one[i]).split()
print(str_one)
else:
print('There is no relation')
if __name__ == '__main__':
str_one = input('Put your First String: ').split()
str_two = input('Put your Second String: ')
print(revers_e(str_one, str_two))
How can I remove a letter that occurs in both strings from the first string then print it?
How about a simple pythonic way of doing it
def revers_e(s1, s2):
print(*[i for i in s1 if i in s2]) # Print all characters to be deleted from s1
s1 = ''.join([i for i in s1 if i not in s2]) # Delete them from s1
This answer says, "Python strings are immutable (i.e. they can't be modified). There are a lot of reasons for this. Use lists until you have no choice, only then turn them into strings."
First of all you don't need to use a pretty suboptimal way using range and len to iterate over a string since strings are iterable you can just iterate over them with a simple loop.
And for finding intersection within 2 string you can use set.intersection which returns all the common characters in both string and then use str.translate to remove your common characters
intersect=set(str_one).intersection(str_two)
trans_table = dict.fromkeys(map(ord, intersect), None)
str_one.translate(trans_table)
def revers_e(str_one,str_two):
for i in range(len(str_one)):
for j in range(len(str_two)):
try:
if str_one[i] == str_two[j]:
first_part=str_one[0:i]
second_part=str_one[i+1:]
str_one =first_part+second_part
print(str_one)
else:
print('There is no relation')
except IndexError:
return
str_one = input('Put your First String: ')
str_two = input('Put your Second String: ')
revers_e(str_one, str_two)
I've modified your code, taking out a few bits and adding a few more.
str_one = input('Put your First String: ').split()
I removed the .split(), because all this would do is create a list of length 1, so in your loop, you'd be comparing the entire string of the first string to one letter of the second string.
str_one = (str_one - str_one[i]).split()
You can't remove a character from a string like this in Python, so I split the string into parts (you could also convert them into lists like I did in my other code which I deleted) whereby all the characters up to the last character before the matching character are included, followed by all the characters after the matching character, which are then appended into one string.
I used exception statements, because the first loop will use the original length, but this is subject to change, so could result in errors.
Lastly, I just called the function instead of printing it too, because all that does is return a None type.
These work in Python 2.7+ and Python 3
Given:
>>> s1='abcdefg'
>>> s2='efghijk'
You can use a set:
>>> set(s1).intersection(s2)
{'f', 'e', 'g'}
Then use that set in maketrans to make a translation table to None to delete those characters:
>>> s1.translate(str.maketrans({e:None for e in set(s1).intersection(s2)}))
'abcd'
Or use list comprehension:
>>> ''.join([e for e in s1 if e in s2])
'efg'
And a regex to produce a new string without the common characters:
>>> re.sub(''.join([e for e in s1 if e in s2]), '', s1)
'abcd'

Find substring of string w/o knowing the length of string

I have a string x: x = "{abc}{def}{ghi}"
And I need to print the string between second { and second }, in this case def. How can I do this without knowing the length of the string? For example, the string x could also be {abcde}{fghij}{klmno}"
This is where pattern matching is useful:
local x = "{abc}{def}{ghi}"
local result = x:match(".-{.-}.-{(.-)}")
print(result)
.- matches zero or more characters, non-greedy. The whole pattern .-{.-}.-{(.-)} captures what's between the second { and the second }.
Try also x:match(".-}{(.-)}"), which is simpler.
I would go about it in a different manner:
local i, x, result = 1, "{abc}{def}{ghi}"
for w in x:gmatch '{(.-)}' do
if i == 2 then
result = w
break
else
i = i + 1
end
end
print( result )

Resources