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)
Related
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
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.
Hi this is my first post. I am working on homework for my Python course. I have my code nearly complete, however I am having an issue with a line break. I have three pictures showing my results when I submit for the grade. My theory is this is an issue with my loop and that I will need to add a break or change the structure somehow. If you could please also point me in the right direction and not give me the answer for free it would be appreciated. Thank you very much.
https://imgur.com/D34gqwD https://imgur.com/1tYuoPO https://imgur.com/Xw5NjOH
I also have my code below:
string = input('Enter input string: ')
while string != 'q':
if ',' not in string:
print('\nError: No comma in string.')
else:
string = string.replace(' ','')
string_parts = string.split(',')
print('\nFirst word: %s' % string_parts[0])
print('Second word: %s' % string_parts[1])
user_input= input('Enter input string: ')
string = user_input
Comparing, your output and the expected one, I find the only difference to be the absence of the newline (\n) in yours. I don't think there is any problem with the structure of the loop.
Observe where the instructor requires you to put the newlines and just add them in the relevant parts of your loop.
Write programs that read a line of input as a string and print every second letter of the string in Python?
So far I have written:
string=input('Enter String: ')
for char in range(0,len(string),2):
print(len(char))
if i input a string: qwerty
it should print "qet"
You need to keep it much simpler than this. If you enter a word and are looking to slice it at a specific point, use slicing.
Your criteria: qwerty it should print "qet"
So, you are looking to print every second letter:
>>> a = "querty"
>>> a[::2]
'qet'
Slicing works like this:
[from start: from end: step]
So, in your case, you are looking to simply print every second, so you want to make use of your step. So, simply slice leaving the start and end empty, since you want to position yourself at the beginning of the string and then simply go every second. This is the reasoning behind using [::2]
Every second letter should start with index of 1 not 0. So, if your input is "qwerty", you output should be "wry".
Code below may be able to answer your question.
sentence = input("\nPlease enter a string : ")
print("Every second letter of the string " + sentence + " is ", end="")
for i in range(len(sentence)):
if i % 2 == 1:
print(sentence[i] + " ", end="")
I am trying to write a function that checks my input to see whether I have entered the character '?'.
This is what I got so far:
def check_word():
word = []
check = 0
user_input = input('Please enter a word that does not contain ?: ')
for token in user_input.split():
if token == '?':
print('Error')
check_word()
My input: hello?
It is supposed to show 'Error'. But it doesn't show anything. Could you please tell me what wrong it is in my code.
I would use the in operator to do this
def check_word(s):
if '?' in s:
print('Error')
For example
>>> check_word('foobar')
>>> check_word('foo?')
Error
The problem is how you split the string of the user_input.
user_input.split():
The example doesn't contain whitespaces so the condition isn't met. If you want for example to check a sentence with spaces, you should split it like this: user_input.split(' ') to split it on the spaces.
But for this example you have two choices:
1) You can just iterate over the input itself because you want to check every char in the string for whether it's a ?.
That is, change user_input.split(): into simply user_input without splitting. This option is good if you might ever want to add some sort of action for each char.
2) It's very easy just to use in, like this:
if '?' in s:
print('There is a question mark in the string')
This is a very simple solution that you can expand and check for other chars in the string as well.
It's because user_input.split() splits the user_input by whitespace. Since hello? does not contain any whitespaces, token is equal to your input and the loop is executed once.
You should iterate over user_input instead, or simply check if '?' in user_input.