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)
1
  • Can you give an example of what you mean by 'string that is equal to an integer as the integer in an index'? Commented Dec 19, 2018 at 3:41

3 Answers 3

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"
Sign up to request clarification or add additional context in comments.

4 Comments

Is there a way to use a variable as the integer though?
@Turtle yes just where I'm printing it just put variable = int(last_char)
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
Absolutely! That's definitely legal use. please see this 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
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

1 Comment

is there a way to use a string there though?
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]) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.