This question already has answers here:
Extract elements of list at odd positions
(5 answers)
Closed 7 years ago.
I have to do this for school, but I can't work it out. I have to get an input and print ONLY the odd characters. So far I've put the input in a list and I have a while loop (which was a clue on the task sheet), but I can't work it out. Please help:
inp = input('What is your name? ')
name = []
name.append(inp)
n=1
while n<len(name):
print inp[1::2]
I guess thats all you need
You don't need to put the string in a list, a string is already essentially a list of characters (more formally, it is a "sequence").
You can use indexing and the modulus operator (%) for this
inp = input('What is your name? ')
n = 0 # index variable
while n < len(inp):
if n % 2 == 1: # check if it is an odd letter
print(inp[n]) # print out that letter
n += 1
Related
This question already has answers here:
Finding the index of an item in a list
(43 answers)
How can I read inputs as numbers?
(10 answers)
Closed 2 years ago.
Hi new to python and programming in general
I'm trying to find an element in an array based on user input
here's what i've done
a =[31,41,59,26,41,58]
input = input("Enter number : ")
for i in range(1,len(a),1) :
if input == a[i] :
print(i)
problem is that it doesn't print out anything.
what am I doing wrong here?
input returns a string. To make them integers wrap them in int.
inp=int(input('enter :'))
for i in range(0,len(a)-1):
if inp==a[i]:
print(i)
Indices in list start from 0 to len(list)-1.
Instead of using range(0,len(a)-1) it's preferred to use enumerate.
for idx,val in enumerate(a):
if inp==val:
print(idx)
To check if a inp is in a you can this.
>>> inp in a
True #if it exists or else False
You can use try-except also.
try:
print(a.index(inp))
except ValueError:
print('Element not Found')
input returns a string; a contains integers.
Your loop starts at 1, so it will never test against a[0] (in this case, 31).
And you shouldn't re-define the name input.
Please don't declare a variable input is not a good practise and Space is very important in Python
a =[31,41,59,26,41,58]
b = input("Enter number : ")
for i in range(1,len(a),1):
if int(b) == a[i] :
print(i)
I think you want to check a value from your list so your input need to be a Int. But input takes it as String. That's you need to convert it into int.
input is providing you a str but you are comparing a list of ints. That and your loop starts at 1 but your index starts at 0
This question already has answers here:
How can I suppress the newline after a print statement? [duplicate]
(5 answers)
Closed 3 years ago.
I am attempting to print a reversed array (list) of integers as a single line of space-separated numbers.
I've tried to use a for loop and printed each integer separately with a sep = ", " to remove the commas from the list. Should I use the remove() method as one alternative?
n = int(input())
arr = list(map(int, input().rstrip().split()))
for i in arr[::-1]:
print(i, sep = ", ")
Output
2
3
4
1
Should be:
2 3 4 1
Suppose I inputted 4. The expected results should be the exact sequence in the output but in a single line.
IIUC, this is what you look for:
print(*reversed(arr))
If a comma separator is needed, you can write
print(*reversed(arr), sep=", ")
for i in arr[::-1]:
print(i, end = ", ")
This question already has answers here:
Comparing digits in an integer in Python
(3 answers)
Closed 3 years ago.
How to add numbers that begin with 1 to a list?
def digit1x(lx):
list = []
for num in lx:
temp = str(num)
if temp[0]== '1':
list.append(int(temp))
return list
print(digit1x(lx))
updated code, and It works, thank you for your help!
You're thinking of numbers as starting with 1 in their base 10 representation? In that case, you should coerce to a string first before checking the digit:
>>> num = 12345
>>> str(num)
'12345'
>>> str(num)[0]
'1'
you cannot do num[0] if num is an int, for example you can write str(num)[0] == '1'. Don't forget to deal with special cases if any.
The error is occuring because you cannot get the [0] index value of an integer. It is only posible to get an index value of an array or string. Create a variable ('temp'↓) that is the string variable of the [0] index of that integer and then use that in the conditional statement:
This works:
def digit1x(lx):
list = []
for num in lx:
temp = str(lx[num])
if temp[0] == '1':
list.append(temp)
return list
print(digit1x(lx))
The value of temp is the string value of the current item.
'temp[0]' is the first character in temp, and therefore the first character in the current item.
Therefore, if temp[0] equals '1' then the first number in the current item is 1.
This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 4 years ago.
I am trying to make a program where it takes in user input and spits out the input without the letters. I'm really confused on why this isn't working.
numText = input("Give me a list of characters: ") # Gets user input of characters
numList = list(numText) # Turns ^ into list
for char in numList: # Every character in the list
if char.isalpha(): # Checks to see if the character is a letter
numList.remove(char) # Removes the letter from the list
print(numList) # Prints the new list without letters
input("") # Used so the program doesnt shut off
I know this is really dumb so im sorry for asking.
You should not iterate and remove at the same time, instead use a list comprehension.
numText = input("Give me a list of characters: ") # Gets user input of characters
numList = [char for char in numText if not char.isalpha()]
print(numList) # Prints the new list without letters
input("")
This question already has answers here:
Bob Counter in Python
(8 answers)
Closed 8 years ago.
i was wondering if anyone could help me figure out how to write a piece of code that would analyze the input a user would put in and count the amount of times a specific word is occurring.
For example, user is prompted to input a string. types in bobobob. We are searching for how many times "bob" appears in this code, and so the answer would be 3.
If this could be done in a for loop/if-else statement without any imports, i would like to see how.
This is what i have, and for some reason its coming up short on most tests
s = raw_input("string: ")
count = len(s.split("bob"))
print count
for example, if you test hoboboobbobbbobobbopbbobbbpbooboboboobbobovob
you get 7 instead of 8.
I need to be able to do this without regex or any other imports.
If you are just looking for a quick answer this will work!
t = "hoboboobbobbbobobbopbbobbbpbooboboboobbobovob"
l = "bob"
count = 0
for x in range(len(t)-len(l)+1):
if (l == t[x:x+len(l)]):
count += 1
print(count)
You can turn that into a function and pop it in there instead of s.split()
def substring_counter(string, sub_string):
count = 0
for i in range(len(string)-len(sub_string)):
if string[i:i+len(sub_string)] == sub_string:
count += 1
return count
Using list comprehension:
def substring_counter_lc(s, c):
return len([i for i in range(len(s)-len(c)) if s[i:i+len(c)] == c])
In action:
>>> substring_counter('hoboboobbobbbobobbopbbobbbpbooboboboobbobovob', 'bob')
8
>>> substring_counter_lc('hoboboobbobbbobobbopbbobbbpbooboboboobbobovob', 'bob')
8