سؤال

I do my apologizes for the dummy question, but i'm experiencing a weird problem with a simple script that seems correct but doesnt' works as expected

#!/usr/bin/python
import json,sys
obj=json.load(sys.stdin)
oem=obj["_id"]
models = obj.get("modelli", 0)

if models != 0:
        for marca in obj["modelli"]:
                brand=obj["modelli"][marca]
                for serie in brand:
                        ser=brand[serie]
                        for modello in ser:
                                model=modello
                                marca = marca.strip()
                                modello = modello.strip()
                                serie = serie.strip()
                                print oem,";",marca,";",serie,";",modello

It should just cycle an array from a json var and print the output in csv format, but i still get the string containing one withespace at the begin and at the end of each variable (oem, marca, serie, modello) like this

KD-CH884 ; Dell ;  ; 966

This is my very first script in python, i've just followed some simple directives, so i'm missing something or what? Any guess?

هل كانت مفيدة؟

المحلول

The print statement is putting in that whitespace.

From the docs here:

A space is written before each object is (converted and) written, unless the output system believes it is positioned at the beginning of a line.

Use ';'.join(...) instead.

نصائح أخرى

Python is actually stripping the whitespaces out. Its just the print statement:

print oem,";",marca,";",serie,";",modello

.. that is reintroducing the spaces. Try concatenating the variables and display them.

';'.join(filter(None, [oem, marca, serie, modello]))

It will only place the semicolon between two existing strings. If a variable holds the empty string after being stripped '', filtering the None will take it out of the list.

try this:

print "%s;%s;%s;%s" % (oem,marca,serie,modello)

or

print ";".join([oem,marca,serie,modello])
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top