簡體   English   中英

"Python檢查字符串的第一個和最后一個字符"

[英]Python Checking a string's first and last character

誰能解釋一下這段代碼有什么問題?

str1='"xxx"'
print str1
if str1[:1].startswith('"'):
    if str1[:-1].endswith('"'):
        print "hi"
    else:
        print "condition fails"
else:
    print "bye"   

我得到的輸出是:

Condition fails

但我希望它會打印hi

當你說[:-1]你正在剝離最后一個元素。 您可以像這樣對字符串對象本身應用startswithendswith ,而不是對字符串進行切片

if str1.startswith('"') and str1.endswith('"'):

所以整個程序就像這樣

>>> str1 = '"xxx"'
>>> if str1.startswith('"') and str1.endswith('"'):
...     print "hi"
>>> else:
...     print "condition fails"
...
hi

更簡單,使用條件表達式,就像這樣

>>> print("hi" if str1.startswith('"') and str1.endswith('"') else "fails")
hi

你應該使用

if str1[0] == '"' and str1[-1] == '"'

要么

if str1.startswith('"') and str1.endswith('"')

但不是切片和檢查一起開始/結束,否則你將切斷你正在尋找的...

您正在測試字符串減去最后一個字符

>>> '"xxx"'[:-1]
'"xxx'

注意最后一個字符""不是切片輸出的一部分。

我想你只想測試最后一個角色; 使用[-1:]切片最后一個元素。

但是,沒有必要在這里切片; 只需直接使用str.startswith()str.endswith()

設置字符串變量時,它不保存它的引號,它們是其定義的一部分。 所以你不需要使用:1

嗨,您也可以試試這個網站 pretagteams.com 來檢查 python 中字符串的第一個或最后一個字符<\/a>

myString.charAt(0)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM