473,785 Members | 2,506 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to get size of unicode string/string in bytes ?

Hello,

how can I get the number of byte of the string in python?
with "len(string )", it doesn't work to get the size of the string in
bytes if I have the unicode string but just the length. (it only works
fine for ascii/latin1) In data structure, I have to store unicode
string for many languages and must know exactly how big of my string
which is stored so I can read back later.

Many thanks for any suggestion.

cheers!
pattreeya.

Aug 1 '06 #1
7 7627
e.g. I use utf8 as encoding/decoding,
s = "ทดสà¸*ภš"
u = s.decode("utf-8")
how can I get size of u ?

pa*******@gmail .com schrieb:
Hello,

how can I get the number of byte of the string in python?
with "len(string )", it doesn't work to get the size of the string in
bytes if I have the unicode string but just the length. (it only works
fine for ascii/latin1) In data structure, I have to store unicode
string for many languages and must know exactly how big of my string
which is stored so I can read back later.

Many thanks for any suggestion.

cheers!
pattreeya.
Aug 1 '06 #2
pa*******@gmail .com wrote:
how can I get the number of byte of the string in python?
with "len(string )", it doesn't work to get the size of the string in
bytes if I have the unicode string but just the length. (it only works
fine for ascii/latin1) In data structure, I have to store unicode
string for many languages and must know exactly how big of my string
which is stored so I can read back later.
I do not quite know what you could possibly need that for, but AFAICT Python
only uses two different unicode encodings depending on the platform.

If 'sys.maxunicode ' is bigger than 65536, you're on a 32 bit unicode platform
(UCS4), otherwise you're on UCS. For UCS4, you can multiply the length of the
unicode string by 4 to get the length of the internal memory buffer, otherwise
multiply it by 2.

Normally, however, you should not need to deal with this kind of detail. Since
you say "read back later", maybe what you actually want is a serialisation of
the unicode string in, say, UTF-8 or something, that you can actually write to
a file and read back.

Stefan
Aug 1 '06 #3
Stefan Behnel wrote:
pa*******@gmail .com wrote:
> how can I get the number of byte of the string in python?
with "len(string )", it doesn't work to get the size of the string in
bytes if I have the unicode string but just the length. (it only works
fine for ascii/latin1) In data structure, I have to store unicode
string for many languages and must know exactly how big of my string
which is stored so I can read back later.

I do not quite know what you could possibly need that for, but AFAICT
Python only uses two different unicode encodings depending on the
platform.
It is very important for relational databases, as these usually constrain
the amount of bytes per column - so you need the size of bytes, not the
number of unicode characters.

Diez
Aug 1 '06 #4
I got the answer. What I need was so simple but I was blinded at that
moment.
Thanks for any suggestion!
--------

f = open("test.csv" , rb)
t1 = f.readline()
>>t2 = t1.decode("iso-8859-9") # test with turkish
t2
u'Dur-kalk trafi\u011fi, t\u0131kan\u013 1kl\u0131k tehlikesi\n'
>>print t2
Dur-kalk trafigi, tikaniklik tehlikesi
>>len(t2)
39
>>t2 = t1.decode("iso-8859-9")
t2
u'Dur-kalk trafi\u011fi, t\u0131kan\u013 1kl\u0131k tehlikesi\n'
>>print t2
Dur-kalk trafigi, tikaniklik tehlikesi
>>len(t2)
39
>>u1 = t2.encode("utf-8")
u1
'Dur-kalk trafi\xc4\x9fi, t\xc4\xb1kan\xc 4\xb1kl\xc4\xb1 k tehlikesi\n'
>>print u1
Dur-kalk trafigi, tikaniklik tehlikesi
>>len(u1)
43
>>>


Thnx!

Aug 1 '06 #5
Diez B. Roggisch wrote
Stefan Behnel wrote:
>pa*******@gmail .com wrote:
>> how can I get the number of byte of the string in python?
with "len(string )", it doesn't work to get the size of the string in
bytes if I have the unicode string but just the length. (it only works
fine for ascii/latin1) In data structure, I have to store unicode
string for many languages and must know exactly how big of my string
which is stored so I can read back later.
I do not quite know what you could possibly need that for, but AFAICT
Python only uses two different unicode encodings depending on the
platform.

It is very important for relational databases, as these usually constrain
the amount of bytes per column - so you need the size of bytes, not the
number of unicode characters.
So then the easiest thing to do is: take the maximum length of a unicode
string you could possibly want to store, multiply it by 4 and make that the
length of the DB field.

However, I'm pretty convinced it is a bad idea to store Python unicode strings
directly in a DB, especially as they are not portable. I assume that some DB
connectors honour the local platform encoding already, but I'd still say that
UTF-8 is your best friend here.

Stefan
Aug 1 '06 #6
So then the easiest thing to do is: take the maximum length of a unicode
string you could possibly want to store, multiply it by 4 and make that
the length of the DB field.
However, I'm pretty convinced it is a bad idea to store Python unicode
strings directly in a DB, especially as they are not portable. I assume
that some DB connectors honour the local platform encoding already, but
I'd still say that UTF-8 is your best friend here.
It was your assumption that the OP wanted to store the "real"
unicode-strings. A moot point anyway, at it is afaik not possible to get
their contents in byte form (except from a C-extension).

And assuming 4 bytes per character is a bit dissipative I'd say - especially
when you have some 80% ascii-subset in your text as european and american
languages have.

The solution was given before: chose an encoding (utf-8 is certainly the
most favorable one), and compute the byte-string length.

Diez
Aug 1 '06 #7
Diez B. Roggisch wrote:
>So then the easiest thing to do is: take the maximum length of a unicode
string you could possibly want to store, multiply it by 4 and make that
the length of the DB field.
>However, I'm pretty convinced it is a bad idea to store Python unicode
strings directly in a DB, especially as they are not portable. I assume
that some DB connectors honour the local platform encoding already, but
I'd still say that UTF-8 is your best friend here.

It was your assumption that the OP wanted to store the "real"
unicode-strings. A moot point anyway, at it is afaik not possible to get
their contents in byte form (except from a C-extension).
It is possible:
>>u"a\xff\uffff \U0010ffff".enc ode("unicode-internal")
'a\x00\xff\x00\ xff\xff\xff\xdb \xff\xdf'

This encoding is useless though, as you can't use it for reencoding on
another platform. (And it's probably not what the OP intended.)
And assuming 4 bytes per character is a bit dissipative I'd say - especially
when you have some 80% ascii-subset in your text as european and american
languages have.
That would require UTF-32 as an encoding, which Python currently doesn't
have.
The solution was given before: chose an encoding (utf-8 is certainly the
most favorable one), and compute the byte-string length.
Exactly!

Servus,
Walter
Aug 2 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
5277
by: Bill Eldridge | last post by:
I'm trying to grab a document off the Web and toss it into a MySQL database, but I keep running into the various encoding problems with Unicode (that aren't a problem for me with GB2312, BIG 5, etc.) What I'd like is something as simple as: CREATE TABLE junk (junklet VARCHAR(2500) CHARACTER SET UTF8)); import MySQLdb, re,urllib
30
2766
by: aurora | last post by:
I have long find the Python default encoding of strict ASCII frustrating. For one thing I prefer to get garbage character than an exception. But the biggest issue is Unicode exception often pop up in unexpected places and only when a non-ASCII or unicode character first found its way into the system. Below is an example. The program may runs fine at the beginning. But as soon as an unicode character u'b' is introduced, the program boom...
43
3793
by: Vladimir | last post by:
Method UnicodeEncoding.GetMaxByteCount(charCount) returns charCount * 2. Method UTF8Encoding.GetMaxByteCount(charCount) returns charCount * 4. But why that? Look: /* Each Unicode character in a string is defined by a Unicode scalar value, also called ...
3
7773
by: hunterb | last post by:
I have a file which has no BOM and contains mostly single byte chars. There are numerous double byte chars (Japanese) which appear throughout. I need to take the resulting Unicode and store it in a DB and display it onscreen. No matter which way I open the file, convert it to Unicode/leave it as is or what ever, I see all single bytes ok, but double bytes become 2 seperate single bytes. Surely there is an easy way to convert these mixed...
10
8107
by: Nikolay Petrov | last post by:
How can I convert DOS cyrillic text to Unicode
15
2120
by: John Salerno | last post by:
Forgive my newbieness, but I don't quite understand why Unicode is still something that needs special treatment in Python (and perhaps elsewhere). I'm reading Dive Into Python right now, and it constantly refers to a 'regular string' versus a 'Unicode string' and how you need to convert back and forth. But why isn't Unicode considered a regular string by now? Is it for historical reasons that we still use ASCII and Latin-1? Why can't...
40
3250
by: apprentice | last post by:
Hello, I'm writing an class library that I imagine people from different countries might be interested in using, so I'm considering what needs to be provided to support foreign languages, including asian languages (chinese, japanese, korean, etc). First of all, strings will be passed to my class methods, some of which based on the language (and on the encoding) might contain characters that require more that a single byte.
2
401
by: willie | last post by:
Martin v. Löwis: Thanks for the thorough explanation. One last question about terminology then I'll go away :) What is the proper way to describe "ustr" below? <type 'unicode'>
5
3032
by: Holger Joukl | last post by:
Hi there, I consider the behaviour of unicode() inconvenient wrt to conversion of non-string arguments. While you can do: u'17.3' you cannot do:
0
9485
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10356
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10161
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10098
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6743
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5390
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4058
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3662
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2890
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.