How to make word inputs in Python
I want to be able to have the computer to ask a question to the user like
test = int(input('This only takes a number as an answer'))
I want to be able to have 'test' not be a number, rather a word, or letter.
Just remove the int call! That is what makes the statement accept integer numbers only.
I.e, use:
test = input('This takes any string as an answer')
Remove the type cast to int
test = input('This only takes a word as an answer :')
A demo
>>> test = input('This only takes a word as an answer :')
This only takes a word as an answer :word
>>> test
'word'
Note - From the docs
The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that
Therefore input automatically converts it to a str and there is no need of any explicit cast.
This should work:
test = str(input('This only takes a string as an answer: '))
BUT
Because Python works with String by default, actually you don't need any casting like int or str
Also, if you were using version prior to 3.x, it would be raw_input instead of input. Since your solution seem to have been accepting input, I can be safe assuming that your Python is OK.
test = input('This only takes a string as an answer')
test = input("This only takes a number as an answer")
test = raw_input("This only takes a number as an answer")
Either one should work
If you are using python 2.7, just use raw_input function.
test = raw_input('This only takes a string as an answer: ')
I.e.:
>>> test = raw_input('This only takes a string as an answer: ')
This only takes a string as an answer: 2.5
>>> type (test)
<type 'str'>
If you use input, you can have only a number:
Right input:
>>> test = input('This only takes a number as an answer: ')
This only takes a string as an answer: 2.5
>>> type (test)
<type 'float'>
Wrong input:
>>> test = input('This only takes a number as an answer: ')
This only takes a number as an answer: word
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'word' is not defined
Related
stringinput = (str(input("Enter a word to start: ")))
removeinput = (str(input("How many character's do you want to remove?")))
if (str)(removeinput) > (str)(stringinput):
print("Cannot remove more chars than there are chars, try again")
else:
removed = stringinput[-1,-removeinput,1]
print((str)(removed))
Traceback (most recent call last):
File "C:\Users\x\PycharmProjects\pythonProject\Pynative Beginner Tasks.py", line 110, in <module>
removed = stringinput[-1,-removeinput,1]
TypeError: bad operand type for unary -: 'str'
I am doing an exercise to create an input that slices a string.
I understand that removeinput needs to be converted to a string to be part of the slice but I don't know how to convert it in the else statement.
I also need it to be a string to make a comparison incase the user inputs a number greater than the amount of chars in stringinput
It looks like you might be trying to take a slice from anywhere in the string, in which case you would need to get an input for the starting index and an ending index. In the example below I wrote it to remove the number of characters from the end of the string so if you input "hello" and "2" you are left with "hel". This behavior could be modified using the tutorial I have attached below.
Here's a modified version of your code with comments to explain the changes:
stringinput = input("Enter a word to start: ")
removeinput = int(input("How many character's do you want to remove? ")) // the int() function converts the input (a string) into an integer
if removeinput > len(stringinput):
print("Cannot remove more chars than there are chars, try again")
else:
removed = stringinput[:-removeinput] // remove the last characters based on the input
print(removed)
In your code you use (str)(removeinput) and (str)(stringinput). It looks like you are trying to cast the variables as strings, but this is not necessary as both of them are already strings by default. In the modified code I converted the input into an integer using int(). This is because your input is not an integer, it is the string version of the integer. By using int(), we are comparing the integer version of the input.
To address the error that you were getting, the syntax that you are using is not correct. Strings are indexed using colons in Python, not commas. Here is a tutorial that might help you: https://www.digitalocean.com/community/tutorials/how-to-index-and-slice-strings-in-python-3
I hope this helps!
Given a string. Replace in this string all the numbers 1 by the word one.
Example input:
1+1=2
wished output:
one+one=2
I tried the following but does not work with an int:
s=input()
print(s.replace(1,"one"))
How can I replace an integer?
You got a TypeError like below.
Use '1' of type str as first argument (string instead number) because you want to work with strings and replace parts of the string s.
Try in Python console like:
>>> s = '1+1=2'
>>> print(s.replace(1,"one"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: replace() argument 1 must be str, not int
>>> print(s.replace('1',"one"))
one+one=2
or simply use the string-conversion method str():
s.replace(str(1), 'one')
Whilst you could simply use a replace(), I would suggest instead using a python dictionary. Defining each number to a word, that would then switch. Like this.
conversion = {
1: 'one',
2: 'two'
}
You can then use this like a dictionary
print(conversion[1]) # "one"
print(conversion[2]) # "two"
This simply makes your code more adaptable, in case you want to convert some numbers and not all. Just an alternative option to consider.
Trying to build an uppercase to lowercase string converter in Python 3.7, this is my code:
def convertChar(char):
if char >= 'A' and char <= 'Z':
return chr(ord(char) + 32)
def toLowerCase(string):
for char in string:
string = string + convertChar(char)
return string
string = input("Enter string - ")
result = toLowerCase(string)
print(result)
And this is my output:
Enter string - HELlo
Traceback (most recent call last):
File "loweralph.py", line 11, in <module>
string = toLowerCase(result)
File "loweralph.py", line 6, in toLowerCase
result = result + convertChar(char)
TypeError: can only concatenate str (not "NoneType") to str
I am really new to Python and I saw answers for 'list to list' TypeErrors and one other answer for str to str, but I couldn't relate it to my code. If somebody could explain what I'm doing wrong, it would be great!
You need to add some exception cases to your code. Firstly, what if the entered character is already lower case?
You can do something of this sort:
def convertChar(char):
if char >= 'A' and char <= 'Z':
return chr(ord(char) + 32)
return char
This might not be the most ideal solution, but it will take care of most of the things. That is, only if the entered character is upper case, it is converted to lower case. For all other cases (whether it is a lower case character, a number et cetra), the character is returned as it is.
Secondly, if you are making a upper case to lower case converter, output of HElLo should be hello, not HElLohello.
For this, you need to modify your second function as follows:
def toLowerCase(string):
newString = []
for char in string:
newString.append(convertChar(char))
return ''.join(newString)
Finally, you might want to consider using .upper() in-built function.
Example of usage:
'HeLlo'.upper()
As coldspeed has commented, when you pass lower case letter to convertChar, the function won't return a proper character. Hence the error.
Also, with 'string = string + convertChar(char)' you are appending to the same input string. This is wrong. You need to use a new empty string for that.
I don't know the reason for building your own method, but you could use the built-in lower() method instead. For example:
my_string = input("Enter string - ")
result = my_string.lower()
print(result)
I've been having trouble getting a specific print in Python 3.4
Input:
str=input("Input Here!!!:")
num = len(str)
x = num
print (((str))*x)
but I'm looking for an output that prints str x times, without using a loop.
for example if I enter:
Input Here!!!: Hello
I would get:
>>>Hello
>>>Hello
>>>Hello
>>>Hello
>>>Hello
You need to add a newline if you want the output on different lines:
In [10]: n = 5
In [11]: s = "hello"
In [12]: print((s+"\n")* n)
hello
hello
hello
hello
hello
It is not possible to get the output as if each string were the output of a new command. The closest to your expected output will be the code above.
You should never use built-in keywords, types for variable names. str is a built in type like list, int etc. Next time you would try to use it, will give you errors.
Ex -
>>> str = 'apple'
Now let's try to build a simple list of no.s as string.
>>> [ str(i) for i in range(4)]
Traceback (most recent call last):
File "<pyshell#298>", line 1, in <module>
[ str(i) for i in range(4)]
TypeError: 'str' object is not callable
Since we have already replaced our str with a string. It can't be called.
So let's use 's' instead of 'str'
s=input("Input Here!!!:")
print ( s * len(s) )
If you want output in different lines
print ( (s+"\n")* len(s) )
I don't know what exactly do you want to achieve. We can always replicate looping with a recursive function.
def input(s):
print(s)
def pseudo_for(n, my_func, *args):
if n==0:
return
else:
'''
Write function or expression to be repeated
'''
my_func(*args)
pseudo_for(n-1, my_func, *args)
pseudo_for(5, input, "Hello")
You can use join with a list comprehension:
>>> s='string'
>>> print('\n'.join([s for i in range(5)]))
string
string
string
string
string
Technically a list comprehension is a 'loop' I suppose, but you have not made clear what you mean by 'without using a loop'
You can also use string formatting in Python:
>>> fmt='{0}\n'*5
>>> fmt
'{0}\n{0}\n{0}\n{0}\n{0}\n'
>>> print(fmt.format('hello'))
hello
hello
hello
hello
hello
But that will have an extra \n at the end (as will anything using *n)
As Tim points out in comments:
>>> print('\n'.join([s]*5))
string
string
string
string
string
Is probably the best of all...
I am looking for a single line command in python to convert an integer input to list.
The following is the situation.
mylist=[]
mylist=list(input('Enter the numbers: '))
The above line works perfectly if i give more than one number as input. Eg 1,2,3 . But it gives Error when i give only a single digit entry. Eg: 1 . Saying it cannot convert an integer to list.
I don't want to run a loop asking user for each input. So i want a one line command which will work for one or more digits input given by user separated by commas.
Thanking you,
-indiajoe
I think that the simplest thing that you can do is:
mylist = map(int, raw_input('Enter the numbers: ').split(','))
But it's nearly the same that using a list comprehension.
You should use raw_input and convert to int with a list comprehension:
user_input = raw_input('Enter the numbers: ')
my_list = [int(i) for i in user_input.split(',')]
From the offical documentation: raw_input reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
input eval()'s what you type. So, when you type 1,2,3, the result is a tuple; when you type 1, the result is an int. Try typing 1, instead of 1. Note that your first line (mylist=[]) is unnecessary.