分离的可变进3个变量,并经过删除的部分文本

问题描述 投票:-1回答:3

我有一个变量,first_line这在1888,60,-32的格式,我要分开这一点,例如,等于x = 1888 y = 60z = -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,
}
python python-3.x variables
3个回答
0
投票

你接近,你所需要的全部是使用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)

0
投票

1.You可以分割使用功能拆分字符串。 2.您可以分配表达式是一个集合到一个以上的变量的结果。

所有上面写的样子,在代码:

x, y, z =your_string.split(',')

只要改变引号。(从iPhone编写)

© www.soinside.com 2019 - 2024. All rights reserved.