Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do Python strings end in a terminating NULL?

Tags:

python

Is there a special character on the end of Python strings? Like it is \0 in C or C++. I want to count length of string in python without using the builtin len function.

like image 961
ayushgp Avatar asked Jun 25 '14 13:06

ayushgp


People also ask

Are strings always null-terminated?

All character strings are terminated with a null character. The null character indicates the end of the string. Such strings are called null-terminated strings. The null terminator of a multibyte string consists of one byte whose value is 0.

Are UTF-8 strings null-terminated?

Yes, UTF-8 defines 0x0 as NUL .

Why do strings end with null character?

When we write some string using double quotes (“…”), then it is converted into null terminated strings by the compiler. The size of the string may smaller than the array size, but if there are some null character inside that array, that will be treated as the end of that string.


1 Answers

There is no end-of-string character in Python, at least not one that is exposed and it would be implementation dependent. String objects maintain their own length and it is not something that you need to be concerned with. There are several ways to get the string's length without using len().

str = 'man bites dog'
unistr = u'abcd\u3030\u3333'

# count characters in a loop
count = 0
for character in str:
    count += 1
>>> count
13

# works for unicode strings too
count = 0
for character in unistr:
    count += 1
>>> count
6

# use `string.count()`
>>> str.count('') - 1
13
>>> unistr.count(u'') - 1
6

# weird ways work too
>>> max(enumerate(str, 1))[0]
13
>>> max(enumerate(unistr, 1))[0]
6
>>> str.rindex(str[-1]) + 1
13
>>> unistr.rindex(unistr[-1]) + 1
6

# even weirder ways to do it
import re
pattern = re.compile(r'$')
match = pattern.search(str)
>>> match.endpos
13
match = pattern.search(unistr)
>>> match.endpos
6

I suspect that this is just the tip of the iceberg.

like image 155
mhawke Avatar answered Sep 27 '22 17:09

mhawke