2015-07-11 30 views
0

我工作在PyCharm分配,並一直負責下列問題:在Python中使用字符串切片來查找字符串前半部分的長度?

的LEN()函數用來計算一個字符串多少個字包含的內容。獲取字符串的前半部分,存儲在變量「phrase」中。

注意:記住類型轉換。

這裏是我到目前爲止的代碼,它給了我:

phrase = """ 
It is a really long string 
triple-quoted strings are used 
to define multi-line strings 
""" 

first_half = len(phrase) 
print(first_half) 

我不知道該怎麼做。我需要使用字符串切片來查找字符串「phrase」的前半部分。任何幫助讚賞。我爲我的無知道歉。

+1

如果我有一個三明治的長度是12英寸,我切片6英寸,我有什麼? –

+0

那麼奇數字母的字符串呢? – Sasha

+0

first_half = len(短語)/ 2獲得半長度,我認爲你使用的是python3,你必須使用'// 2'這就是他們正在談論的類型轉換 – The6thSense

回答

1

嘗試類似:

first_half = len(phrase) 
print(phrase[0:first_half/2]) 

這將需要更智能的處理奇數長度的字符串。有關切片的更多信息,請參見question

+1

例如,如果字符串爲5個字符,則在Python 3中將切分2.5個字符。 –

+1

我不想爲他做所有他的功課;) – nalyd88

+0

@MalikBrahimi你怎麼能切片2-1/2個字符? – wwii

2

只是切片串的前半部分,一定要在事件使用//該字符串奇數長度的,如:

print phrase[:len(phrase) // 2] # notice the whitespace in your literal triple quote 
0

注意:請記住有關類型轉換。

在Python 2的區別將產生一個int,但是在Python 3,你要使用一個int師這樣half = len(phrase) // 2

下面是一個Python 2.0版本

>>> half = len(phrase)/2 
>>> phrase[:half] 
'\nIt is a really long string\ntriple-quoted st' 

無需在phrase[0:half]0phrase[:half]看起來更好:)

+0

我已經提到過。 –

0

試試這個print(string[:int(len(string)/2)])

len(string)/2正常返回小數所以這就是爲什麼我用int()

0

使用slicingbit shifting(這會更快,你應該做的很多次):

>>> s = "This is a string with an arbitrary length" 
>>> half = len(s) >> 1 
>>> s[:half] 
'This is a string wit' 
>>> s[half:] 
'h an arbitrary length' 
+2

我覺得這是毫無意義的。右移與2分相同。 –

+0

它給你相同的結果,但它確實工作得更快。如果OP(或任何未來的讀者)需要執行這樣的操作幾百萬次,那將比使用分割更快。 – IanAuld

1
first_half = phrase[:len(phrase)//2] or phrase[:int(len(phrase)/2)] 
0

試試這個:

phrase = """ 
It is a really long string 
triple-quoted strings are used 
to define multi-line strings 
""" 
first_half = phrase[0: len(phrase) // 2] 
print(first_half)