2 # Copyright (C) 2007-2013 EDF R&D
4 # This library is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU Lesser General Public
6 # License as published by the Free Software Foundation; either
7 # version 2.1 of the License.
9 # This library is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 # Lesser General Public License for more details.
14 # You should have received a copy of the GNU Lesser General Public
15 # License along with this library; if not, write to the Free Software
16 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 """Module rassemblant des fonctions utilitaires de manipulations
21 de chaines de caractères
23 # module identique à Execution/strfunc.py pour usage dans Eficas
31 """Return local encoding
36 _encoding = locale.getpreferredencoding() or 'ascii'
42 def to_unicode(string):
43 """Try to convert string into a unicode string."""
44 if type(string) is unicode:
46 elif type(string) is dict:
48 for k, v in string.items():
49 new[k] = to_unicode(v)
51 elif type(string) is list:
52 return [to_unicode(elt) for elt in string]
53 elif type(string) is tuple:
54 return tuple(to_unicode(list(string)))
55 elif type(string) is not str:
57 assert type(string) is str, u"unsupported object: %s" % string
58 for encoding in ('utf-8', 'iso-8859-15', 'cp1252'):
60 s = unicode(string, encoding)
62 except UnicodeDecodeError:
64 return unicode(string, 'utf-8', 'replace')
67 def from_unicode(ustring, encoding, errors='replace'):
68 """Try to encode a unicode string using encoding."""
70 return ustring.encode(encoding)
73 return ustring.encode(encoding, errors)
76 def convert(content, encoding=None, errors='replace'):
77 """Convert content using encoding or default encoding if None."""
78 if type(content) not in (str, unicode):
79 content = unicode(content)
80 if type(content) == str:
81 content = to_unicode(content)
82 return from_unicode(content, encoding or get_encoding(), errors)
85 def ufmt(uformat, *args):
86 """Helper function to format a string by converting all its arguments to unicode"""
87 if type(uformat) is not unicode:
88 uformat = to_unicode(uformat)
89 if len(args) == 1 and type(args[0]) is dict:
90 arguments = to_unicode(args[0])
94 if type(arg) in (str, unicode, list, tuple, dict):
95 nargs.append(to_unicode(arg))
96 elif type(arg) not in (int, long, float):
97 nargs.append(to_unicode(str(arg)))
100 arguments = tuple(nargs)
103 formatted_string = uformat % arguments
104 #except UnicodeDecodeError:
105 # print type(uformat), uformat
106 # print type(arguments), arguments
110 return formatted_string