Python字符串以NULL结尾吗?

问题描述:

Python字符串的末尾是否有特殊字符?像C或C++中的\ 0一样。 我想计算python中字符串的长度,而不使用内置的len函数。Python字符串以NULL结尾吗?

+1

看起来像家庭作业。你有什么尝试? –

+3

在Java中它不是NULL ... –

+0

@AamirAdnan我试图使用与我们在Java或C++中执行的相同的操作来检查字符串的结尾。 – ayushgp

Python中没有字符串末尾的字符,至少没有一个是暴露的,它将取决于实现。字符串对象保持自己的长度,这不是你需要关心的事情。有几种方法可以在不使用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 

我怀疑这只是冰山一角。

+0

使用正则表达式来获取字符串的长度?这是我今天看到的最有趣的事情。 – Shuklaswag

count=0 
for i in 'abcd': 
    count+=1 
print 'lenth=',count 

其他方式:

for i,j in enumerate('abcd'): 
    pass 
print 'lenth=',i+1 

enumerate是一个内置的函数,返回的元组(索引和值)

例如:

l= [7,8,9,10] 
print 'index','value' 
for i ,j in enumerate(l): 
    print i,j 

输出:

index value 
0  7 
1  8 
2  9 
3  10 

+0

枚举是做什么的?这段代码中j的用法是什么? – ayushgp

+0

@ayushgp现在检查 –

+0

谢谢,但仍然有一个问题,如果有任何字符串字符的结尾是什么? – ayushgp

l = "this is my string" 
counter = 0 
for letter in l: 
    counter += 1 

>>> counter 
17 

为了回答这个问题你问的问题:没有终止空或类似的东西在一个Python字符串的结束(你可以看到),因为你没有办法让字符串“结束”。在内部,最流行的Python实现是用C语言编写的,所以在底层可能有一个以NULL结尾的字符串。但是作为Python开发人员,这对你来说是完全不透明的。

如果你想在不使用内建函数的情况下获得长度,你可以做很多不同的事情。这里有一个选项是不同于其他人发布在这里:

sum([1 for _ in "your string goes here"]) 

这是,在我看来,有点更优雅。

+1

Python可能不会在内部使用空终止,因为字符串可以包含空值:'\ 0'(echos'\ x00') –

一些有趣的事情,我发现:

s_1 = '\x00' 
print ("s_1 : " + s_1) 
print ("length of s_1: " + str(len(s_1))) 

s_2 = '' 
print ("s_2 : " + s_2) 
print ("length of s_2: " + str(len(s_2))) 

if s_2 in s_1: 
    print ("s_2 in s_1") 
else: 
    print ("s_2 not in s_1") 

输出是:

s_1 : 
length of s_1: 1 
s_2 : 
length of s_2: 0 
s_2 in s_1 

这里S_1似乎是一个'和S_2似乎是一个 '' 或NULL。