Given the following string:
my_string = "fan_num=2,fan1=0,fan2=0,chain_xtime8={X0=8,X1=3,X2=11},chain_offside_6=0,chain_offside_7=0,chain_offside_8=0,chain_opencore_6=0,chain_opencore_7=0,chain_opencore_8=0"
How can I split it such that I get the following output:
[
fan_num=2,
fan1=0,
fan2=0,
chain_xtime8={X0=8,X1=3,X2=11},
chain_offside_6=0,
chain_offside_7=0,
chain_offside_8=0,
chain_opencore_6=0,
chain_opencore_7=0,
chain_opencore_8=0
]
I've tried:
output = my_string.split(',')
However, that splits the chain_xtime8 value which is not what I want. I am using Python 2.7.
Through a series of convoluted replacements, I converted this style into JSON. Then using json.loads you can convert it into a Python dict. This ASSUMES you do not use the characters being replaced and you continue only using integers as values
This can obviously be tightened up but I wanted to leave it readable
import json
my_string = "fan_num=2,fan1=0,fan2=0,chain_xtime8={X0=8,X1=3,X2=11},chain_offside_6=0,chain_offside_7=0,chain_offside_8=0,chain_opencore_6=0,chain_opencore_7=0,chain_opencore_8=0"
my_string = '{"' + my_string + '"}'
my_string = my_string.replace('=', '":"')
my_string = my_string.replace(',', '","')
my_string = my_string.replace('"{', '{"')
my_string = my_string.replace('}"', '"}')
myDict = json.loads(my_string)
pprint of myDict results :
{'chain_offside_6': '0',
'chain_offside_7': '0',
'chain_offside_8': '0',
'chain_opencore_6': '0',
'chain_opencore_7': '0',
'chain_opencore_8': '0',
'chain_xtime8': {'X0': '8', 'X1': '3', 'X2': '11'},
'fan1': '0',
'fan2': '0',
'fan_num': '2'}
Also one more example -
print(myDict['chain_xtime8']['X0'])
>> 8
Related
I am trying to split a string by ",".
'split' function works fine for the following 'example1' as expected.
example1 = "1,'aaa',337.5,17195,.02,0,0,'yes','abc'"
example1.split(",")
Result: ['1', "'aaa'", '337.5', '17195', '.02', '0', '0', "'yes'", "'abc'"]
But, here i have a scenario, where there are commas within the single quotes, on which i do not want to split on.
example2 = "1,'aaa',337.5,17195,.02,0,0,'yes','abc, def, xyz'"
example2.split(",")
Result: ["1,'aaa',337.5,17195,.02,0,0,'yes','abc,", 'def,', "xyz'"]
But I am trying to get this result instead:
['1', "'aaa'", '337.5', '17195', '.02', '0', '0', "'yes'", "'abc, def, xyz'"]
How can I achieve this with string split function?
You should first try to use built-ins or the standard library to read in your data as a list, for instance directly from a CSV file via the csv module.
If your string is from a source you cannot control, adding opening and closing square brackets gives a valid list, so you can use ast.literal_eval:
from ast import literal_eval
example2 = "1,'aaa',337.5,17195,.02,0,0,'yes','abc, def, xyz'"
res = literal_eval(f'[{example2}]')
# [1, 'aaa', 337.5, 17195, 0.02, 0, 0, 'yes', 'abc, def, xyz']
This does convert numeric data to integers / floats as appropriate. If you would like to keep them as strings, as per #JonClements' comment, you can pass to csv.reader:
import csv
res = next(csv.reader([example2], quotechar="'"))
# ['1', 'aaa', '337.5', '17195', '.02', '0', '0', 'yes', 'abc, def, xyz']
Assuming that you want to keep those 's around the elements ("'aaa'" instead of 'aaa' as in your expected output), here's how you may do it with a function:
def spl(st, ch):
res = []
temp = []
in_quote = False
for x in st:
if (x == "'"):
in_quote = not in_quote
if (not in_quote and x == ch):
res.append("".join(temp))
temp = []
else:
temp.append(x)
res.append("".join(temp))
return res
example2 = "1,'aaa',337.5,17195,.02,0,0,'yes','abc, def, xyz'"
print(spl(example2, ','))
Output:
['1', "'aaa'", '337.5', '17195', '.02', '0', '0', "'yes'", "'abc, def, xyz'"]
I'm writing some code, and I want to search through this list and remove all the 1s at the beginning. Once it hits a 0 I want it to stop and that be the new list. Whenever I have 13 total characters it does what I want - converted = ("1111111011110") but when I have the full 16, converted = ("1111111111011110") it leaves an extra two ones at the beginning.....
Here's my code:
converted = ("1111111111011110")
finalL = []
i = 0
for x in converted:
finalL.append(x)
print(finalL)
for x in finalL:
if finalL[0] == "1":
finalL.remove("1")
print(finalL)
right now it prints the first list:
['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '0', '1', '1', '1', '1', '0']
but then this list: ['1', '1', '0', '1', '1', '1', '1', '0']
I want the second print to print ['0', '1', '1', '1', '1', '0']
If you only have onces and zeros, and you only care for the string from the first zero and beyond, I would do something like the following.
string = '1111111110111111110'
first_zero = string.find('0')
new_string = string[first_zero:] #'0111111110'
Note that this will not work for strings with only ones because find will return -1, which will be the last character of your string. So you would need to make sure that every time a -1 is returned your string is nothing actually.
Or by following your example with loops:
converted = '1111111110111111110'
finalL = ''
for i,elem in enumerate(converted):
if elem=='0':
# if a zero is found, copy the whole string from
# this position
finalL = converted[i:]
break
I have a code like this:
def datauji(self):
uji = []
for x in self.fiturs:
a = [x[0],x[-5:]] #I think the problem in this line
uji.append(a)
return uji
with open('DataUjiBaru.csv','wb') as dub:
testing = csv.writer(dub)
datatest = d.datauji()
datatest.pop(0)
for x in datatest:
testing.writerow(x)
I want to pair the value in self.fiturs, In self.fiturs:
F37,0,1,0,1,1,1,0,1,0,2,1,0,0,0,1
F10,8,4,3,3,3,6,8,5,8,4,8,4,5,6,4
F8,1,0,2,0,0,0,2,0,0,0,0,0,2,0,0
So i want to pair index[0] and index[-5:] and write it to the csv, and the output on the csv like this:
F37,"['1', '0', '0', '0', '1']"
F10,"['8', '4', '5', '6', '4']"
F8,"['0', '0', '2', '0', '0']"
My Expectation in that csv is like this:
F37,1,0,0,0,1
F10,8,4,5,6,4
F8,0,0,2,0,0
How can I fix that?
You were correct about the issue with your code, it is found in the line:
a = [x[0],x[-5:]]
This creates nested items that look like this:
['F37', ['1', '0', '0', '0', '1']]
Here are two ways to fix this:
Option 1 - Use the splat* operator:
a = [x[0],*x[-5:]]
Option 2 - Concatenate two slices of your list:
a = x[:1] + x[-5:]
Both of these will remove the nesting of your lists, and instead give you lines looking like:
['F37', '1', '0', '0', '0', '1']
Which you can then write to your output file.
This question already has answers here:
Convert string to list. Python [string.split() acting weird]
(2 answers)
Closed 5 years ago.
In python3, I'd like to turn a string, like this:
my_str = "['1', '2', '3', '4', '72']"
into a list, like this:
my_list = ['1', '2', '3', '4', '72']
Is there a simple way to do this?
Many thanks, y'all.
Use ast.literal_eval:
>>> import ast
>>> my_str = "['1', '2', '3', '4', '72']"
>>> ast.literal_eval(my_str)
['1', '2', '3', '4', '72']
This is a much more safer option than using eval() because it fails if the data isn't safe.
import re
my_str = "[1', '2', '3', '4', '72']"
re.compile(r'(\d+)').findall(my_str)
['1', '2', '3', '4', '72']
Note: Using re you can get the desired output even if you had not put that ' in the string.
Hi I would like to split the following string "1234" in ['1', '2', '3', '4'] in python.
My current approach is using re module
import re
re.compile('(\d)').split("1234")
['', '1', '', '2', '', '3', '', '4', '']
But i get some extra empty strings. I am not an expert in regular expressions, what could be a proper regular expression in python to accomplish my task?
Please give me some advices.
Simply use list function, like this
>>> list("1234")
['1', '2', '3', '4']
The list function iterates the string, and creates a new list with all the characters in it.
Strings are by default character lists:
>>> nums = "1234"
>>> for i in nums:
... print i
...
1
2
3
4
>>> nums[:-1]
'123'