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.
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.
Yes, UTF-8 defines 0x0 as NUL .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With