0

Was wondering how you would use a string that is equal to an interger as the integer in an 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)
Turtle
  • 49
  • 1
  • 7
  • Can you give an example of what you mean by 'string that is equal to an integer as the integer in an index'? – najeem Dec 19 '18 at 03:41

3 Answers3

2

This will get you the last letter in a word without all the code. I'm unsure what you're asking by index though.

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

Example:

Enter word: Test
#"t"

If you're asking if "Test 1" was input and you want to get the last character as a number then it's as simple as wrapping it in int but do some checking first.

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

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

Examples:

Enter word: Test 1
#1

Enter word: Test
#"t"
Jab
  • 26,853
  • 21
  • 75
  • 114
  • Is there a way to use a variable as the integer though? – Turtle Dec 19 '18 at 03:42
  • @Turtle yes just where I'm printing it just put `variable = int(last_char)` – Jab Dec 19 '18 at 03:44
  • but in the array index thing, like if i made num=2 is there a way i could do word1[num], word2[num], word3[(num-1)], etc – Turtle Dec 19 '18 at 03:48
  • 1
    Absolutely! That's definitely legal use. please see [this](https://stackoverflow.com/a/509295/225020) great answer to understand better what's going on in mine and @KayEss's answer. but as long as the num is within `0 -- len(word)-1` then `word[num]` will return that character in the string – Jab Dec 19 '18 at 03:54
1

The simplest way with python is to index using -1. Negative indexes count from the end of the string so word[-1] will always give you the last letter

KayEss
  • 2,290
  • 15
  • 31
1

Here I am giving you few of the examples including above.

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]) 
hygull
  • 8,464
  • 2
  • 43
  • 52