如何从 python IO 流中删除最后一个字符
How to remove last char from python IO stream
import io
my_list = [{'id': 1, 'updated_at': 20}, {'id': 2, 'updated_at': 10} ]
string_out = io.StringIO()
first_obj = my_list[0]
keys = first_obj.keys()
for i in keys:
string_out.write(i)
string_out.write(",")
print(string_out.getvalue())
输出:- id,updated_at,
我想从我的信息流中删除最后一个“,”(逗号)。?
我想删除最后一个可能是任何字符的字符我在这里使用命令只是为了举例。
你可以使用 join
和 ,
来写,比如,
>>> import io
>>> my_list = [{'id': 1, 'updated_at': 20}, {'id': 2, 'updated_at': 10} ]
>>> string_out = io.StringIO()
>>> first_obj = my_list[0]
>>> keys = first_obj.keys()
>>> string_out.write(','.join(keys))
13
>>> print(string_out.getvalue())
id,updated_at
>>>
或更好,
>>> string_out = io.StringIO()
>>> my_list
[{'id': 1, 'updated_at': 20}, {'id': 2, 'updated_at': 10}]
>>> for idx,d in enumerate(my_list):
... if idx == 0:
... string_out.write(','.join(d.keys()) + '\n')
... string_out.write(','.join(str(x) for x in d.values()) + '\n')
...
14
5
5
>>> print(string_out.getvalue())
id,updated_at
1,20
2,10
这可以通过在元素之前添加逗号并有一个标志来确保在第一个元素之前不添加逗号来解决
import io
my_list = [{'id': 1, 'updated_at': 20}, {'id': 2, 'updated_at': 10} ]
string_out = io.StringIO()
first_obj = my_list[0]
keys = first_obj.keys()
flag=0
for i in keys:
if(flag==0):
flag=1
else:
string_out.write(",")
string_out.write(i)
print(string_out.getvalue())
import io
my_list = [{'id': 1, 'updated_at': 20}, {'id': 2, 'updated_at': 10} ]
string_out = io.StringIO()
first_obj = my_list[0]
keys = first_obj.keys()
for i in keys:
string_out.write(i)
string_out.write(",")
print(string_out.getvalue())
输出:- id,updated_at,
我想从我的信息流中删除最后一个“,”(逗号)。?
我想删除最后一个可能是任何字符的字符我在这里使用命令只是为了举例。
你可以使用 join
和 ,
来写,比如,
>>> import io
>>> my_list = [{'id': 1, 'updated_at': 20}, {'id': 2, 'updated_at': 10} ]
>>> string_out = io.StringIO()
>>> first_obj = my_list[0]
>>> keys = first_obj.keys()
>>> string_out.write(','.join(keys))
13
>>> print(string_out.getvalue())
id,updated_at
>>>
或更好,
>>> string_out = io.StringIO()
>>> my_list
[{'id': 1, 'updated_at': 20}, {'id': 2, 'updated_at': 10}]
>>> for idx,d in enumerate(my_list):
... if idx == 0:
... string_out.write(','.join(d.keys()) + '\n')
... string_out.write(','.join(str(x) for x in d.values()) + '\n')
...
14
5
5
>>> print(string_out.getvalue())
id,updated_at
1,20
2,10
这可以通过在元素之前添加逗号并有一个标志来确保在第一个元素之前不添加逗号来解决
import io
my_list = [{'id': 1, 'updated_at': 20}, {'id': 2, 'updated_at': 10} ]
string_out = io.StringIO()
first_obj = my_list[0]
keys = first_obj.keys()
flag=0
for i in keys:
if(flag==0):
flag=1
else:
string_out.write(",")
string_out.write(i)
print(string_out.getvalue())