2014-06-25 61 views
9

Python字符串的末尾是否有特殊字符?像C或C++中的\ 0一樣。 我想計算python中字符串的長度,而不使用內置的len函數。Python字符串以NULL結尾嗎?

+1

看起來像家庭作業。你有什麼嘗試? –

+3

在Java中它不是NULL ... –

+0

@AamirAdnan我試圖使用與我們在Java或C++中執行的相同的操作來檢查字符串的結尾。 – ayushgp

回答

9

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

2
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

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

>>> counter 
17 
1

爲了回答這個問題你問的問題:沒有終止空或類似的東西在一個Python字符串的結束(你可以看到),因爲你沒有辦法讓字符串「結束」。在內部,最流行的Python實現是用C語言編寫的,所以在底層可能有一個以NULL結尾的字符串。但是作爲Python開發人員,這對你來說是完全不透明的。

如果你想在不使用內建函數的情況下獲得長度,你可以做很多不同的事情。這裏有一個選項是不同於其他人發佈在這裏:

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

這是,在我看來,有點更優雅。

+1

Python可能不會在內部使用空終止,因爲字符串可以包含空值:'\ 0'(echos'\ x00') –

3

一些有趣的事情,我發現:

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。

相關問題