For a game that asks input from the user, I am using an if check to determine what the user said. It's for a text based game here, so when a user inputs "examine table" I want examine to become a variable and table to become another variable so I can evaluate them separately in my script.
A variable named "move" is used for the input.
move = input("> ")
I want that variable to split into "action" and "object" variables by splitting the two words in half.
How would I go around doing this?
verb, _, params = move.partition(" ")
verb will be first word
_ will be the separator, whitespace in this case
params will be the rest after the verb
First you want to get the input:
varName = raw_input("Enter anything: ")
Then you want to split the input
splitted_results = varName.split()
print splitted_results
This will give you a list of strings split by empty space. You can loop through as so:
for sr in splitted_results:
print sr
Are you asking how to split a string into 2 different variables?
If so,
string = 'examine table'
splitString = string.split()
giving you the list
['examine','table']
Is it a string? If so, split up the string by whatever character you want to with
string.split("[character to split by here]")
Then, you will get an array. If you only wanted to split by the first character (let's say for example a period):
arr = string.split(".")
arr = [arr[0], ','.join(arr[1:])]
Related
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)
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.
This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 4 months ago.
I am trying to write a function that takes a user inputted list, and transforms it into a string that separates each value inside the list with a comma, and the last value in the list with "and". For example, the list ['cats', 'dogs', 'rabbits', 'bats'] would be transformed to: 'cats, dogs, rabbits, and bats'.
My code works if I assign a list to a variable and then pass the variable to my newString function, but if I pass a user input to my function, it will treat every character in the user input as a separate list value.
So my question is, how can I tell Python that I want input() to be read as a list. Is this even possible? I am very new to Python and programming in general, so Lists and Tuples is about as far as I know so far. I am learning dictionaries now. My code is printed below, thanks.
def listToString(aList):
newString = ''
for i in range(len(aList) - 1):
newString += aList[i] + ', '
newString = newString + 'and ' + aList[-1]
return(newString)
spam = list(input())
print(listToString(spam))
input() always gives you just a string.
You can analyze that string depending on how the user is supposed to enter the list.
For example, the user can enter it space separated like 'cats dogs rabbits bats'. Then you do
input_list = input().split()
print(listToString(input_list))
You can also split on , or any delimiter you like.
If you want to read a list literal from user input, use ast.literal_eval to parse it:
import ast
input_list = ast.literal_eval(input()) # or ast.literal_eval(raw_input()) on Python 2
You could build a list from the input and use your current working code to format it as you want.
def get_user_input():
my_list = []
print('Please input one word for line, leave an empty line to finish.')
while True:
word = input().strip()
if word:
my_list.append(word)
else:
break
return my_list
I want to turn the string:
avengers,ironman,spiderman,hulk
into the list:
['avengers','ironman','spiderman','hulk']
I tried
list = raw_input("Enter string:")
list = list.split()
but it's not working the right way as I need it, it's taking the whole string and makes it as one item in the list (it works fine without the "," but that's not what I need)
If you dont pass anything to split method, it splits on empty space. Pass the comma as argument:
my_list.split(',')
edited so you dont use list as name
Hello guys i want to make for example the next string:
avengers,ironman,spiderman,hulk into the next list:
['avengers','ironman','spiderman','hulk']
i tried that `
list = raw_input("Enter string:")
list = list.split()
Do this instead:
list = raw_input("Enter string:")
list = list.split(",")
And, as mentioned by the others, you might want to not use the name "list" for your string/array.
Hello i am trying to make my program check for certain words in the user input. For example: The user types "add the numbers 6+6" what the programs does is it has a dictionary and checks the words in the dictionary and compares them to the words in the user input this example is "add". If the word add is in the user input then it checks for numbers and also math symbols this example is "6+6" then it outputs the answer?
I have tried:
if test == "add":
do something
but this will not work unless the word "add" is all by itself. any help is very much appreciated.
It will work only in the cases like add 6+6 or 6+6 add or add <some_text> 6+6 etc.
string = input()
if 'add' in string:
string = string.split('+')
no1 = int(string[0].split()[-1])
no2 = int(string[1].split()[0])
print(no1 + no2)
You can loop through the input words and check them in your dictionary like
for word in input:
if word in dic:
pass
fail
You can use the string.split() to split up the text into each word.
Then you can test each word individually for key words.
Details: http://docs.python.org/2/library/string.html
Look up the split method.
I'm pretty sure the split method by default returns a list of words split up by white space characters. So for example:
test_list = input.split()
test_list[1] should be 'add'
Best way to find out is to test it yourself, but I think it is something along those lines.
Cheers