簡體   English   中英

Python-如何在索引中使用字符串

[英]Python - How to use string in index

想知道如何將等於整數的字符串用作索引中的整數。

word = input("Enter word:")
print(word)
letterNum = int(len(word)) #determines amount of letters in word
print(letterNum)
lastLetter = word[letterNum] #supposed to figure out the last letter in a word
print(lastLetter)

這將使您獲得單詞的最后一個字母,而無需輸入所有代碼。 我不確定您在按索引查詢什么。

word = input("Enter word: ")
print(word[-1])

例:

Enter word: Test
#"t"

如果您要詢問是否輸入了"Test 1" ,並且想獲取最后一個字符作為數字,則就像將其包裝為int一樣簡單,但是首先要進行一些檢查。

word = input("Enter word: ")
last_char = word[-1]

if isnumeric(word[-1]):
    print(int(last_char))
else:
    print(last_char)

例子:

Enter word: Test 1
#1

Enter word: Test
#"t"

python最簡單的方法是使用-1進行索引。 負索引從字符串末尾開始計數,因此word[-1]總是會給您最后一個字母

在這里,我僅提供一些上述示例。

word = input("Enter word:").strip() # strip() is used to remove any trailing or leading white spaces
print(word)
letterNum = int(len(word)) # Determines amount of letters in word
print(letterNum)

# 1st way (Using the internet that we created above) 
lastLetter = word[letterNum - 1] # Supposed to figure out the last letter in a word
print(lastLetter)

# 2nd way (As the above answers suggest, -ve index, -1 for last, -2 for 2nd last, this is best, but this basically for Python, other language like C/C++ etc. use 1st way) 
print(word[-1]) 

# 3rd way (Not good, but it is good for those who are learning Python,Reversing the string and printing 1st character) 
print(word[::-1][0]) 

暫無
暫無

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

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