Python: Taking end 3 characters in a string from a user input - python

I have an algorithm which I want to run in Python. It wants me to get 2 inputs from the user, then extract the last 3 letters of each input, then output these 2 sets of extracted characters side by side. I know how to extract end characters from a given array but am struggling to work out the correct syntax for extracting end characters from a user input.
Got as far as...
fname = input("What is your firstname? ")
flength = len(fname)
sname = input("What is your surname? ")
slength = len(sname)
...understanding that I need to know the length of the input to find the last 3 characters of it...
for x in range(flength):print(flength)
...then tested the loop runs for the exact length of the input, so far so good, but the next syntax I would usually use are ones for an array. Can an input be converted into an array perhaps? Is there an easier way to achieve this I am overlooking?
Thanks!

You don't need to know the length, nor use a loop, use the slicing notation on strings str[start:end:step]
Along with negative indices, to start from end
fname = input("What is your firstname? ")
sname = input("What is your surname? ")
print(fname[-3:])
print(sname[-3:])
What is your firstname? johnny
What is your surname? Philivitch
nny
tch

Use the slicing operation [-3:] to get the last three characters (-3 in a slice means "three characters from the end"):
>>> print(input("What is your firstname? ")[-3:], input("What is your surname? ")[-3:])
What is your firstname? Daniel
What is your surname? Gough
iel ugh

Related

Python exercise, guidance for slicing substrings

Please write a program which asks the user to type in a string. The program then prints out all the substrings which begin with the first character, from the shortest to the longest. Have a look at the example below.
Please type in a string: test
t
te
tes
test
Obviously my code is not the way it supposed to be:
stg = input("Please type in a string: ")
print(stg[0])
print(stg[0:5])
print(stg[0:10])
print(stg[10:50])
print(stg[:])
ok, this is a homework and I don't give you the exact solution... but as some points:
you have a string and want to print first 1 letter, first 2 letters and so on... so your range end must increase one by one...
you don't know about input length so you can't use hard code and use a loop
for loop you need to know about string length and use a builtin method for getting the length...
any question? ask it...
userString = input("Gimme String: ")
# Looping based on the given String
# Last Value is not included so you need to increment the value by one
for i in range(len(userString)):
# Last Value is not included so you need to increment the value by one
print(userString[:i+1])
#Alternative
for i in range(1,len(userString)+1):
print(userString[:i])
stg = input("Please type in a string: ")
print("\n".join([stg[0:i+1] for i in range (len(stg))]))
Output:
t
te
tes
test
Just use simple for loop
stg = 'test'
temp_str = ''
for i in range(len(stg)):
temp_str = temp_str + stg[i]
print(temp_str)

Finding the values corresponding with user input from a list of tuples

As a foreword, I'm quite new to python, and coding in general.
I'm trying to get the following code to find the specific values in the foodgroups tuple that match with user input (ie: Dairy, Nuts, and Grain) and attach them to Output (ie: Dairy and Nuts). The line with Output was gotten from another website when I was first making this. The code works when the user provides an input that only contains one item without any symbols or spaces (ie: Dairy) but anything extra causes Output to be blank when printed.
userinput = input("Enter foodgroups ate in the last 24hrs : ").title()
foodgroups = ("Dairy","Nuts","Seafood","Chocolate")
Output = list(filter(lambda x:userinput in x, foodgroups))
if foodgroups[0] or foodgroups[1] or foodgroups[2] or foodgroups[3] in userinput:
print(Output,"is present in your list, " + userinput)
else:
print("Negative.")
I've thought of swapping around foodgroups and userinput, but that results in a TypeError, and turning the tuple into a string has Output always return blank.
I've asked others how to fix this, but they've had no better luck. Any help is appreciated!
If userinput is a comma separated string then split it and use a list:
userinput = input("Enter foodgroups ate in the last 24hrs : ")
foodgroups = ("Dairy","Nuts","Seafood","Chocolate")
uin = userinput.split(",")
grp = []
for x in uin:
if x in foodgroups:
grp.append(x)
grp is the user defined foods in foodsgroup
The main thing is that you want to use split to separate individual words from the user input into a list of words. I also swapped x and seafoods in your lambda.
If the user separates each word by one or more spaces, here's how to change your code to work:
userinput = input("Enter foodgroups ate in the last 24hrs : ").title()
foodgroups = ("Dairy","Nuts","Seafood","Chocolate")
userfoods = userinput.split()
Output = list(filter(lambda x: x in userfoods, foodgroups))
print(Output,"is present in your list, " + str(userinput))
As other's mention, you need to use split() to separate individual items in the input:
userfoods = userinput.split()
But even after that your if condition isn't correct:
if foodgroups[0] or foodgroups[1] or foodgroups[2] or foodgroups[3] in userinput:
The thing to realize here is that or and in are operators that only work with the immediately adjacent 2 values. We can add parentheses to see how this works:
if (((foodgroups[0] or foodgroups[1]) or foodgroups[2]) or (foodgroups[3] in userinput)):
This means that foodgroups[0] or foodgroups[1] evaluates to just the value of foodgroups[0], so foodgroups[1] is basically ignored. This isn't what you want. Instead, you need to check in for each item:
if foodgroups[0] in userinput or foodgroups[1] in userinput or foodgroups[2] in userinput or foodgroups[3] in userinput:
But as you can see this gets very lengthy. So using a loop or list comprehension or generator expression can reduce the amount of code you need to write as others have already shown.

Putting multiple numbers from an input into one list

I'm trying to put multiple interest rates from one input into a list. I'm assuming just putting a comma between them wont separate them into different variables in the list? Is there a way I can get them all into a list in one input or do i need to run the input multiple times and add one each time?
interest_rates_list = []
while True:
investment = input("Please enter the amount to be invested ")
periods = input("Please enter the number of periods for investment maturity ")
if int(periods) < 0:
break
interest_rates = input("Please enter the interest rate for each period ")
interest_rates_list.append(interest_rates)
If you input is something like:
4 5 12 8 42
then you can simply split it up by space and assign to values list:
values = input().split()
If your input something like 4,5,12, then you need to use split(',').
You can split the input string into several string and then convert it to float. This can be done in one line.
interest_rates = list(map(float, interest_rates.split(",")))
Here I go a step further, your next move will be to calculate some return based on interest rates, and so you will need float/integer to do so.
The python string function split can accept a delimiter character and split the input string into a list of values delimited by that character.
interest_rates = input("Please enter the interest rate for each period ")
interest_rates_list = interest_rates.split(",")
If you take the input, you can convert it to a string by using:
str(interest_rates)
Let this be variable A
So, A = str(interest_rates)
Now, to seperate each entry of the interest rates, we do:
interest_rates_list = A.split(' ')
This function literally splits the string at all spaces and returns a list of all the broken pieces.
NOTE: if you do A.split(*any string or character*) it'll split at the mentioned character. Could be ',' or ';' or ':', etc.
Now you can iter over the newly formed list and convert all the numbers stored as string to ints or floats by doing
for i in interest _rates_list:
i = float(i) #or int(i) based on your requirement

How to check if every character of the string is different?

I was just wondering, how to check if I ask a person to input a string, how do I check if every character inside that string is different?
For an example:
string = str(input("Input a string: ")
I would like to do it with a while loop. So, if two characters in a string are different, it stays in the loop and prompts the user to input the string again.
If I understand your question correctly, you want to reject any string that contains more than one copy of the same character. If a string with duplicated characters is entered, you want to repeat the prompt and get another input.
The easiest way to do the duplicate check is to create a set from your string and then check if the set has the same length as the original. If there were any duplicates in the string, they'll be present only once in the set.
while True:
input_string = input("Enter a string")
if len(set(input_string)) == len(input_string):
break
print("Please avoid repeating any characters")
You could also try this:
while True:
b = input("Enter a string: ")
if all([b[i] not in b[:i] + b[i+1:] for i in range(len(b))]):
break
print("Please try again!")

How do I gather user numerical input into a list in Python?

I'm new to Python and am trying to make a simple program to calculate mean median and mode from numbers input by user. So far I have:
num=[]
UserNumbers=int(input("Enter number sequence separated by spaces: "))
num.append(UserNumbers)
print (num)
I want the user to be able to input multiple int's separated by spaces, however my code only accepts one number. The mean/median/mode part shouldn't be hard as I'm just going to use statistics package in 3.4; just need help with gathering input.
You have to parse the answer if you want it this way.
UserNumbers=input("Enter number sequence separated by spaces: ")
nums = [int(i) for i in UserNumbers.split()]
EDIT:
Duplicate of this question
You can use this one line:
user_numbers = [int(num) for num in raw_input
("Enter number sequence separated by spaces: ").split()]
Notes:
Read about PEP-8
Read about split
List comprehension

Categories