我有一个变量,first_line
这在1888,60,-32
的格式,我要分开这一点,例如,等于x = 1888
y = 60
和z = -32
,但是它们可能是不同的长度,例如,另外一个是768,60,-13776
。
我有tried this并没有让我的文字分成变量。
write.py
# open current file and read first line
with open(currentfile) as f:
first_line = f.readline()
first_line = first_line.rstrip()
print(currentfile)
print(first_line)
# define fullnamejson as END + first_line + .json
fullnamejson = "END_" + first_line + ".json"
# define fullname as END + first_line
fullname = "END_" + first_line
os.rename(currentfile, fullnamejson)
print(fullnamejson)
# define x y and z
x = "some value x"
y = "some value y"
z = "some value z"
# define formatted as what will be written to the file
formatted = "{\n \"id\": \"" + fullname + "\",\n \"name\": \"END\",\n \"icon\": \"waypoint-normal.png\",\n \"x\": " + x + ",\n \"y\": " + y + ",\n \"z\": " + z + ",\n}"
print(formatted)
# write to file
with open(fullnamejson, "w") as text_file:
##print(f(fullnamejson), file=text_file)
print(f'{formatted}', file=text_file)
zzz_split_1.txt
(输入)
1888,60,-32
fullnamejson
(输出)
{
"id": "END_1888,60,-32",
"name": "END",
"icon": "waypoint-normal.png",
"x": some value x,
"y": some value y,
"z": some value z,
}
你接近,你所需要的全部是使用split
的内容划分!
f=open("a.txt", "r")
if f.mode == 'r':
contents =f.read()
f.close()
arr = contents.split(",")
fullnamejson = "END_" + contents + ".json"
print(fullnamejson)
fullname = "END_" + contents
formatted = "{\n \"id\": \"" + fullname + "\",\n \"name\": \"END\",\n \"icon\": \"waypoint-normal.png\",\n \"x\": " + contents[0] + ",\n \"y\": " + contents[1] + ",\n \"z\": " + contents[2] + ",\n}"
print(formatted)
with open(fullnamejson, "w") as text_file:
print(f'{formatted}', file=text_file)
1.You可以分割使用功能拆分字符串。 2.您可以分配表达式是一个集合到一个以上的变量的结果。
所有上面写的样子,在代码:
x, y, z =your_string.split(',')
只要改变引号。(从iPhone编写)