I'm currently doing a project for my university, and one of the assignments was to get python to only print the odd characters in a string, when I looked this up all I could find were string slicing solutions which I was told not to use to complete this task. I was also told to use a loop for this as well. Please help, thank you in advance.
Here is my code so far, it prints the string in each individual character using a for loop, and I need to modify it so that it prints the odd characters.
i = input("Please insert characters: ")
for character in i:
print(character)
Please follow this code to print odd numbered characters
#Read Input String
i = input("Please insert characters: ")
#Index through the entire string
for index in range(len(i)):
#Check if odd
if(index % 2 != 0):
#print odd characters
print(i[index])
Another option:
a= 'this is my code'
count = 1
for each in list(a):
if count % 2 != 0:
print(each)
count+=1
else:
count+=1
I think more information would be helpful to answer this question. It is not clear to me whether the string only contains numbers. Anyway, maybe this answers your question.
string = '38566593'
for num in string:
if int(num) % 2 == 1:
print(num)
To extend on Kyrubas's answer, you could use-
string = '38566593'
for i, char in enumerate(string):
if i % 2 == 1:
print(char)
person = raw_input("Enter your name: ")
a = 1
print"hello " , person
print "total : " , len(person)
for each in list (person):
if a % 2 ==0:
print "even chars : " , (each)
a+=1
else:
a+=1
s = raw_input()
even_string=''
odd_string=''
for index in range(len(s)):
if index % 2 != 0:
odd_string = odd_string+s[index]
else:
even_string = even_string+ (s[index])
print even_string,odd_string
Try this code. For even index start you can use range(0, len(s), 2).
s = input()
res = ''
for i in range(1,len(s),2):
res +=s[i]
print(res)
When we want to split a string, we can use the syntax:
str[beg:end:jump]
When we put just one number, this number indicates the index.
When we put just two numbers, the first indicates the first character (included) and the second, the last character (excluded) of the substring
You can just read the string and print it like this:
i = input("Please insert characters: ")
print(i[::2])
When you put str[::] the return is all the string (from 0 to len(str)), the last number means the jump you want to take, that meaning that you will print the characters 0, 2, 4, etc
You can use gapped index calling. s[start:end:gap]
s = 'abcdefgh'
print(s[::2])
# 'aceg'
returning the characters with indexes 0, 2, 4, and 6. It starts from position 0 to the end and continues with a gap of 2.
print(s[1::2])
# 'bdfh'
Returning the characters with indexes 1, 3, 5, and 7. It starts from position 1 and goes with a gap of 2.
Related
I know it can be simply done through string slicing but i want to know where is my logic or code is going wrong. Please Help!
S=input()
string=""
string2=""
list1=[]
list1[:0]=S
for i in list1:
if(i%2==0):
string=string+list1[i]
else:
string2=string2+list1[i]
print(string," ",string2)
Here's my code. Firstly i stored each character of string in the list and went by accessing the odd even index of the list.
But i'm getting this error
if(i%2==0):
TypeError: not all arguments converted during string formatting
You are iterating over characters, not indices, so your modulo is incorrect, equivalent to:
i = "a"
"a" % 2 == 0
You want to use enumerate
for idx, letter in enumerate(list1):
if(idx%2 == 0)
string += letter
You don't need to use an intermediate list: just iterate over the input string directly. You also need to use for i in range(len(original)) rather than for i in original, because you need to keep track of whether a given character is at an odd or an even index. (I've gone ahead and renamed some of the variables for readability.)
S = input()
even_index_characters = ""
odd_index_characters = ""
for i in range(len(S)):
if i % 2 == 0:
even_index_characters += S[i]
else:
odd_index_characters += S[i]
print(f"{even_index_characters} {odd_index_characters}")
This is a piece of the program for a game of hangman. I am trying to iterate through the hangman word and print the letter guessed by the user if it matches at that index. If it does not it will print an underscore. I am getting the following error for the second if condition: IndexError: string index out of range
while(guessTracker >= 0):
letterGuess= input("Enter a letter for your guess: ")
count=0
wordGuess=""
if letterGuess in hangmanWord:
while count<= len(hangmanWord):
if hangmanWord[count]==letterGuess:
wordGuess= wordGuess+ letterGuess
right= right+1
else:
wordGuess= wordGuess + "_ "
count+=1
print(wordGuess)
In Python (and most other programming languages) string indexes start at 0 so the last position is len(hangmanWord)-1.
You can fix it just by changing <= to <.
Try
while count<= len(hangmanWord)-1:
Because the string's length will never reach the real length (for example: if the word is "hangman", it has a length of 7, but the count starts from 0, and goes up to a maximum of 6, therefor not being able to ever reach the 7th char.
String indexes are from 0 to len(string)-1;
you just need to change your loop like this:
while count < len(hangmanWord):
Indexes are 0-based so you index a string from index 0 up to len(hangmanWord) - 1.
hangmanWord[len(hangmanWord)] will always raise an IndexError.
You should also give a look to the enumerate function that can help with that.
wordGuess = ["_"] * len(hangmanWord)
for index, letter in enumerate(hangmanWord):
if letterGuess == letter:
wordGuess[index] = letter
print("".join(wordGuess))
I am new to python and I was trying to write a program that gives the frequency of each letters in a string from a specific point. Now my code is giving correct output for some inputs like if I give the input "hheelloo", I get the correct output, but if the input is "hheelllloooo", the frequency of h,e and l is printed correct, but the frequency of 'o' comes out as 7 if the starting point is index 0. Can somebody tell me what am i doing wrong.
Write a Python program that counts the occurrence of Character in a String (Do
not use built in count function.
Modify the above program so that it starts counting
from Specified Location.
str = list(map(str, input("Enter the string : ")))
count = 1
c = int(input("Enter the location from which the count needs to start : "))
for i in range(c, len(str)):
for j in range(i+1,len(str)):
if str[i] == str[j]:
count += 1
str[j] = 0
if str[i] != 0:
print(str[i], " appears ", count, " times")
count = 1
str = list(map(str, input("Enter the string : ")))
count = 1
c = int(input("Enter the location from which the count needs to start : "))
for i in range(c, len(str)):
for j in range(i+1,len(str)):
if str[i] == str[j]:
count += 1
str[j] = 0
if str[i] != 0:
print(str[i], " appears ", count, " times")
count = 1 // <----- This line should be outside the if block.
The error was because of indentation.
I have just properly indented the last line.
Thanks, if it works, kindly upvote.
string module can be useful and easy to calculate the frequency of letters, numbers and special characters in a string.
import string
a='aahdhdhhhh2236665111...//// '
for i in string.printable:
z=0
for j in a:
if i==j:
z+=1
if z!=0:
print(f'{i} occurs in the string a {z} times')
If you want to calculate the frequency of characters from a particular index value, you just have to modify the above code a little as follows:
import string
a='aahdhdhhhh2236665111...//// '
c = int(input("Enter the location from which the count needs to start : "))
for i in string.printable:
z=0
for j in a[c:]:
if i==j:
z+=1
if z!=0:
print(f'{i} occurs in the string a {z} times')
I don't think you need to map the input to list of str as input() always returns a string and string itself is a list of characters. Also make sure you don't use the built-ins as your variable names (As str used in your code). One of the simpler approach can be:
input_word = input("Enter the string : ")
c = int(input("Enter the location from which the count needs to start : "))
# Dict to maintain the count of letters
counts = {}
for i in range(c, len(input_word)):
# Increment 1 to the letter count
counts[input_word[i]] = counts.get(input_word[i], 0)+1
for letter, freq in counts.items():
print (f'{letter} appears {freq} times')
Output:
Enter the string : hheelllloooo
Enter the location from which the count needs to start : 2
e appears 2 times
l appears 4 times
o appears 4 times
I'm trying to solve a hacker rank challenge:
Given a string, s , of length n that is indexed from 0 to n-1 , print its even-indexed and odd-indexed characters as 2 space-separated strings. on a single line (see the Sample below for more detail)
link: https://www.hackerrank.com/challenges/30-review-loop/problem
Error:
for example:
The input "adbecf" should output "abc def"
When I run python Visualizer my code seem to have the correct output.. but on hacker rank it's saying I have the wrong answer. Does anyone know what might be wrong with my code.
This is the code I tried -
class OddEven:
def __init__(self, input_statement):
self.user_input = input_statement
def user_list(self):
main_list = list(user_input)
even = []
odd = []
space = [" "]
for i in range(len(main_list)):
if (i%2) == 0:
even.append(main_list[i])
else:
odd.append(main_list[i])
full_string = even + space + odd
return(full_string)
def listToString(self):
my_string = self.user_list()
return(''.join(my_string))
if __name__ == "__main__":
user_input = str(input ())
p = OddEven(user_input)
print(p.listToString())
First of all, input is always string, you don't need to convert it here.
user_input = str(input())
Each line is provided to you as separate input. Number of strings equal to num in the first line. In this case 2, so...
count = input()
for s in range(int(count)):
...
user_input variable inside user_list function should be accessed as self.user_input, it's a property of an object, which you pass to function as self.
Also you can iterate over list directly.
Here:
full_string = even + space + odd
you're trying to concatenate list, which is not a good idea, you'll still get a list.
You can join list with separating them with some string using join string method.
' '.join(list1, list2, ..., listN)
It's better do define odd and even as empty strings.
And then join them the using concatenation (+).
Here:
if (i%2) == 0
you don't have to compare with 0. Python will evaluate what's to the right from condition as True or False. So:
if i % 2:
...
There is simpler solution:
def divide(self):
odd = even = ''
for i, c in enumerate(self.user_input):
if i % 2:
odd += c
else:
even += c
return even + ' ' + odd
Here is the simple code for this problem:)
T=int(input())
for i in range(0,T):
S=input()
print(S[0::2],S[1::2])
First time here (and a programming noob), hope I get the formatting correct!
I'm trying to make a function that will print out where in a list the occurence of a sought after letter is placed. The code below finds the letter and prints out where in the list the letter is i.e. if you search for 'a' the program will answer it's in the 2nd spot (x+1).
The problem is, if I search for a letter that have more than one occurrencies (for example the letter 'e'), the program finds the letter in both spots but in both cases prints out that it is in the 10th spot.
I'm trying to find out why, should be 10th and 17th in this case.
# store string in variable
solution = list('can you guess me')
guess = raw_input('What letter do you guess on? ')
# Search list
def search(guess):
nothing = 0
for x in solution:
if x == guess:
print x,
print "is in ",
print solution.index(x) + 1
nothing = 1
if nothing == 0:
print "Couldn't find ",
print guess
search(guess)
If choosing e, like this:
What letter do you think is in the answer? e
the program prints out:
e is in 11
e is in 11
I would like to know why. :/
How about this approach:
solution = 'This is the solution'
# Search list
def search(guess):
return [i for i,x in enumerate(solution) if x == guess]
guess = raw_input('Enter your guess: ')
result = search(guess)
if result:
positions = ','.join(str(i+1) for i in result)
print('{0} was found in positions {1}'.format(guess, positions))
else:
print('Sorry, {0} was not found!'.format(guess))
What we are doing here is stepping through the solution and if a character matches the guess, we return its position. If no characters match, then the method will return an empty list; which is a falsey value.
Then, we just check the return value of the method. If it is a list, we add 1 to the position (since list indices start from 0), and then print those out.
solution.index(x) does the same search for you, but will only ever return the first match.
Use enumerate() instead to create an index:
for i, x in enumerate(solution):
if x == guess:
print x,
print "is in ",
print i + 1
nothing = 1
The alternative approach would be to tell solution.index() where to start searching from. The previous position you printed, for example:
last = -1
for x in solution:
if x == guess:
print x,
print "is in ",
last = solution.index(x, last) + 1
print last
nothing = 1