Python - How to use string in index - python

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)

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"

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

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])

Related

What does [offset+1:]: mean in this code?

I am new to coding and was asked to write a program that prompts the user to enter two inputs: some text and a word and to find the indices of the code. While I have completed the code, I am still unsure of the process that goes through. I mainly want to know what offset does in this code.
sentence = input("Enter a sentence: ")
word = input("Enter a word : ")
offset = -1
#use if-else to determine if word is in the sentence
if word in sentence:
while word in sentence[offset+1:]:
offset = sentence.index(word, offset+1)
print(offset)
else:
print('Not found.')
Explanation: The offset variable is used to track the position in the sentence. To begin with, the offset is -1. On each iteration of the while loop, the offset is set to the next index position for the starting character of the desired word.
For example, let us assume you have the sentence "if we go, we go together" and the word you are searching for is "we".
Before the start of the while loop, the offset is -1, so [offset+1:] will be from 0 (i.e. offset+1) and to the end of the sentence (i.e. :).
The statement sentence.index(word, offset+1) will then set the offset to the starting index position of the matching word (i.e. 3). On each iteration, this will continue until the word is no longer in the remaining sentence or the end of the sentence has been reached.
Thus, for this example, the offset will be -1 before the loop and then 3, 10 at the end of each iteration.
Alternatively: You can use regular expressions. The code below shows how this can be done:
import re
word = input('Enter word: ')
sentence = input('Enter sentence: ')
indexes = []
for match in re.finditer(word, sentence):
indexes.append(match.start())
if len(indexes):
print('\n'.join(map(str, indexes)))
else:
print(f'The word {word!r} is not in the sentence {sentence!r}')
Output: The following output would be displayed if either of the code in the above explanation is executed:
3
10

How to replace the specified dash with the letter

I wish to write a hangman program and in order to do so, I have to replace the hash ('-') letter(s) with the user's guessed letter (guess). But when I run the code, it replaces all the hashes with the user's guess letter.
The code seems okay but I don't get the desired result.
words is a list of words I have written before the function.
def word_guess():
random.shuffle(words)
word = words[0]
words.pop(0)
print(word)
l_count = 0
for letter in word:
l_count += 1
# the hidden words are shown a '-'
blank = '-' * l_count
print(blank)
guess = input("please guess a letter ")
if guess in word:
# a list of the position of all the specified letters in the word
a = [i for i, letter in enumerate(word) if letter == guess]
for num in a:
blank_reformed = blank.replace(blank[num], guess)
print(blank_reformed)
word_guess()
e.g: when the word is 'funny', and guess is 'n', the output is 'nnnnn'.
How should I replace the desired hash string with guess letter?
it replaces all the hashes
This is exactly what blank.replace is supposed to do, though.
What you should do is replace that single character of the string. Since strings are immutable, you can't really do this. However, lists of strings are mutable, so you could do blank = ['-'] * l_count, which would be a list of dashes, and then modify blank[num]:
for num in a:
blank[num] = guess
print(blank)
A couple things to note:
inefficient/un-pythonic pop operation (see this)
l_count is just len(word)
un-pythonic, unreadable replacement
Instead, here's a better implementation:
def word_guess() -> str:
random.shuffle(words)
word = words.pop()
guess = input()
out = ''
for char in word:
if char == guess:
out.append(char)
else:
out.append('-')
return out
If you don't plan to use the locations of the correct guess later on, then you can simplify the last section of code:
word = 'hangman'
blank = '-------'
guess = 'a'
if guess in word:
blank_reformed = ''.join(guess if word[i] == guess else blank[i] for i in range(len(word)))
blank_reformed
'-a---a-'
(You still have some work to do make the overall game work...)

How do I remove space at the end of an output in python?

I have a program that counts and prints all words in a sentence that contains a specific character(ignoring case).
Code in Python -
item=input()
ip=input().tolower()
r=ip.count(item)
print(r)
ip=ip.split()
for word in ip:
if item in word:
print((word), end=' ')
This program works as expected but for the last word that is printed I don't want a white-space after it.
If anyone could guide me on how to remove the space it would be appreciated.
Why don't you use list comprehension and str.join?
print(' '.join([w for w in ip if item in w]))
I don't think there's a way to remove that, as it's a part of your terminal. Best answer I can give you.
I expanded on the code though, cause I was kinda bored.
sentence = input("Enter a sentence: ").lower()
pull = input("Which character(s) do you want to count?: ").lower()
for c in pull:
occurrences = 0
for character in sentence:
if c == character:
occurrences+=1
if c!=" ": print("\'%s\' appears %d times"%(c, occurrences))
for word in sentence.split():
occurrences = 0
for character in word:
if c == character:
occurrences+=1
if occurrences == 1:
print(("1 time in \'%s\'")%(word))
elif occurrences > 0:
print(("%d times in \'%s\'")%(occurrences,word))
+The solution with a list comprehension appears more concise, but if you prefer an alternative you can use the following. It was tested and worked with the example in the picture.
# Amended solution. The commented lines are the amendment.
item = input('Letter: ')
ip = input('Input: ').lower()
r = ip.count(item)
print(r)
ip = ip.split()
outputString = '' # Added: Initialise an empty string to keep the answer
for word in ip:
if item in word:
outputString += word + ' ' # Changed: Accumulates the answer in a string
print(outputString[:-1]) # Added: Prints all the string's characters
# except the last one, which is the additional space
You're close, just change your print statement from print((word), end=' ') to print((word), end=''). Your print statement has a whitespace for the end but you don't want the whitespace so make the end an empty string.

how to reverse a sentence with a while loop

For an assignment, I need to use a while loop to reverse a list, and I just can't do it.
This is the sample code I have to help me get started:
sentence = raw_int (" ")
length = len(sentence) # determines the length of the sentence (how many characters there are)
index = length - 1 #subtracts one from the length because we will be using indexes which start at zero rather than 1 like len
while... #while the index is greater than or equal to zero continue the loop
letter = sentence[index] #take the number from the index in the sentence and assigns it to the variable letter
I need to use this in my solution.
sentence = raw_input(" ")
length = len(sentence)
index = length - 1
reversed_sentence = ''
while index >= 0:
#letter is the last letter of the original sentence
letter = sentence[index]
#make the first letter of the new sentence the last letter of the old sentence
reversed_sentence += letter
#update the index so it now points to the second to last letter of the original sentence
index = index - 1
print reversed_sentence
Because this is an assignment, I'm not going to give you the full code. But I will give you two 'hints'.
1) a sentenced is reversed if every character is 'flipped'. For example, 'I ran fast'-to flip this sentence first swap 'I' and 'f', then space and 's' and so on.
2) you can use syntax like:
Sentence[i], sentence[len(sentence)-i] = sentence[len(sentence)-i], Sentence[i]
This should definitely be enough to get you going.
You can do:
new_sentence = list()
sentence = list(raw_input(" "))
while sentence:
new_sentence.append(sentence.pop(-1))
else:
sentence = ''.join(new_sentence)

Beginner Issue; string index out of range

# word reverser
#user input word is printed backwards
word = input("please type a word")
#letters are to be added to "reverse" creating a new string each time
reverse = ""
#the index of the letter of the final letter of "word" the users' input
#use this to "steal" a letter each time
#index is the length of the word - 1 to give a valid index number
index = len(word) - 1
#steals a letter until word is empty, adding each letter to "reverse" each time (in reverse)
while word:
reverse += word[index]
word = word[:index]
print(reverse)
print(reverse)
input("press enter to exit")
Working to make a simple program that spells a user input word backwards and prints it back to them by "stealing" letters from the original and making new strings from them.
Trouble I'm having is this code spews back a string index out of range error at
reverse += word[index]
Help or a better way of achieving same result is mucho apreciado.
Reversing a word in python is simpler than that:
reversed = forward[::-1]
I wouldn't use a loop, it's longer and less readable.
While others have pointed out multiple ways of reversing words in Python, here is what I believe to be the problem with your code.
index always stay the same. Lets say the user inputs a four letter word, like abcd. Index will be set to three (index = len(word) - 1). Then during the first iteration of the loop, word will be reduced to abc (word = word[:index]). Then, during the next iteration of the loop, on the first line inside it (reverse += word[index]) you will get the error. index is still three, so you try to access index[3]. However, since word has been cut short there is no longer an index[3]. You need to reduce index by one each iteration:
while word:
reverse += word[index]
word = word[:index]
index -= 1
And here is yet another way of reversing a word in Python (Wills code is the neatest, though):
reverse = "".join([word[i-1] for i in range(len(word), 0, -1)])
Happy coding!
You're going to want to use the "range" function.
range(start, stop, step)
Returns a list from start to stop increasing (or decreasing) by step. Then you can iterate through the list. All together, it would look something like this:
for i in range(len(word) -1, -1, -1):
reverse += word[i]
print(reverse)
Or the easier way would be to use string slicing to reverse the word directly and then iterate through that. Like so:
for letter in word[::-1]:
reverse += letter
print(reverse)
With the way it is written now, it will not only print the word backwards, but it will also print each part of the backwards word. For example, if the user entered "Hello" it would print
o
ol
oll
olle
olleH
If you just want to print the word backwards, the best way is just
print(word[::-1])
It is because you are not changing the value of the index
modification:
while word:
reverse += word[index]
word = word[:index]
index-=1
print(reverse)`
that is you have to reduce index each time you loop through to get the current last letter of the word

Categories

Resources