This code must print every other character using for loops - python

Objective: print every other character from user-inputted string in uppercase values
I inserted a slice but the code won't execute the way I want it to.
python
s=input("Please enter a string: ")
for char in s:
print (char[0::2].upper())
If the user inputs hello, it should print:
H
L
O

You've used two iteration loops; the problem calls for only one.
Your for loops through each character of the string. For input "hello", it will loop five times. char will take on the values h, e, l, l, o in that order.
In the loop body, you've inserted an extra iteration: the string slice [0::2]. First, this second iteration doesn't do anything useful for you. Next, it's wrong, in that you applied it to char, which is a single character, not a string.
You need to apply the alternate-character slicing to the string, not to each of the five characters. Alternately, you can iterate through the five characters and print only the even-numbered ones.
Slicing:
print(s[0::2].upper())
Output:
HLO
Iteration:
for idx, char in enumerate(s):
if idx%2 == 0:
print(char.upper())
Output:
H
L
O

Try this:
s=input("Please enter a string: ")
print(s[0::2].upper())

Related

Additional iteration over a list when shifting text

I've encountered a small problem with a simple shift deciphering.
N,K = [int(s) for s in input().split()]
myres = []
alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
myalph = [a for a in alph]
for i in range(N):
s = input()
mylist = [d for d in str(s)]
for b in range(len(mylist)):
for c in range(len(myalph)):
if mylist[b] == myalph[c]:
mylist[b] = myalph[c-K]
print(myalph[c-K], c-K, b, c)
myres = myres + mylist
Res = [str(i) for i in myres]
print("".join(Res))
The idea is for every character of my input string to be replaced with a different character from the alphabet that's been shifted by a given key (K).
The problem occurs when c-K < 0 and the replacing key is taken from the back of the list. Then the loop is being iterated twice.
If the key is 3 and I input A instead of getting X, I'm getting U as the first iteration gives X but then X is also iterated and becomes U.
Your mistake is looping over all the letters in alph:
The for loop tests all the letters of the alphabet, in order, and 'A' is matched. You set mylist[b] to 'X' (0 - 3 is -3 and myalph[-3] is 'X'.
The loop then continues to test all the other letters of the alphabet against mylist[b], so eventually it gets to 'X', sees that the letter matches and sets mylist[b] to 'U'.
The loop continues to test the remaining letters of the alphabet against mylist[b], and reaches the end without further matches.
At the very least you need to break out of the loop when you have shifted a letter.
But rather than loop, you could use the str.find() method (directly on the alph string) to find a matching index for the letter; it'll be set to -1 if the letter is not found at all:
for b in range(len(mylist)):
c = alph.find(s[b])
if c > -1: # the letter exists
s[b] = alph[c - K]
Aside from that, there are some other improvements you could make:
You can loop over and index into strings directly, there is no need to turn alph into a list here. When you do need to to turn a string into a list of individual characters, you should use list(stringobject). So mylist = list(s) would suffice.
myres is already a list of strings, there is no need to convert each to a string again.
Rather than put all the letters from s into a list, then adding the whole mylist list to res to myres, you could just directly append each letter you processed to myres; that also removes the need to alter myres.
Python variable names do not need to be limited to single characters. Use more descriptive names so that it is easier to understand what your code does when you return to it later.
Taken together, that'd lead to:
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
parts, key = [int(s) for s in input().split()]
results = []
for part in range(parts):
characters = input()
for character in enumerate(characters):
letter_idx = alphabet.index(character)
if letter_idx > -1:
# this is a letter in the alphabet, shift it with the key
character = alphabet[letter_idx - key]
results.append(character)
print("".join(results))

How to print horizontally instead of vertically?

I wrote a script that is supposed to print an answer to a specific input horizontally.
For example if the input is:
TTACTGGCAT
It should print:
TTACTGGCAT
AATGACCGTA
My code:
x = 0
n = input("Insert DNA seqence: ")
print(n.upper())
while x < len(n):
if 'T' in n[x]:
print('A')
if 'G' in n[x]:
print('C')
if 'C' in n[x]:
print('G')
if 'A' in n[x]:
print('T')
x = x + 1
I assume you want to do something like this:
nucl_dict = {'A':'T', 'T':'A', 'C':'G', 'G':'C'}
n = input("Insert DNA seqence: ").upper()
print(n)
print(''.join(nucl_dict.get(nucl, nucl) for nucl in n))
nucl_dict defines which nucleotides are complementary.
This joins the characters for the corresponding nucleotides into a string and prints the result.
If the character is not a valid nucleotide, the character is simply added without a change to the complementary string. get tries to find the value given the first argument as a key (in this case each character in n) and if the key does not exist uses the second argument (in this case the same character).
You should concat everything in a string and after the loops end print it.
You can use the end parameter like print(some_var, end='') to not print ending newline after each call. In your loop you would want to print new line, so just run without the end parameter there. See print documentation.

How to remove characters from the odd numbered string?

If I have a string like this: ABCDE
I want to read two characters at a time (AB then CD) and remove the remaining characters (E) which cannot be read in tuples or in two's. How would I remove those characters?
I have this code below so far:
s = 'ABCDE'
for (first, second) in zip(s[0::2], s[1::2]):
if not first or not second:
if first:
s.replace(first, '')
continue
else:
s.replace(second, '')
continue
print first, second
print s
This code prints (A B C D) which is good but I want to remove that extra E in the for loop which I am trying to do with the if statement. I check if the either the first or second variable of the tuple is an empty string and then remove whichever one isn't an empty string from the original s variable.
This above code doesn't seem to work. Does anyone have a different suggestion or how I can improve this?
If you want to remove the last character in case the string's length is odd:
word = "ABCDE"
if len(word) % 2 == 1:
word = word[:-1]
Now if you want to read the characters two at a time, here is a more instinctive way:
for i in range(len(word) // 2):
print(word[2*i:2*i+2])
The latter will even drop the last character for you.
str = "ABCDE"
for i, k in zip(str[::2], str[1::2]):
print(i + k)
Outputs:
AB
CD

Why do I get this error on python and how do I fix it? (loops and strings)

My code suppose to take a string to a function and then switch the caps of each char in there from h to H and E to e
but I somewhat get an error in my if s
why is that?
This is the error messege:
chr = str[i]
TypeError: string indices must be integers, not str
My code is:
def CapsChanger(str):
i = str[0]
for i in str :
chr = str[i]
if((ord(chr) > 46) and (ord(chr) < 91)):
str[i].upper()
if((ord(chr) > 96) and (ord(chr) < 126)):
str[i].lower()
print str
str = raw_input()
CapsChanger(str)
input()
When you do for i in str, in each iteration i represents that actual character, not the index. So you don't need to do chr = str[i] - i is already that character.
import string
def invertCase(text):
## Creating a list where results will be stored
results = list()
## This will contain the abc in upper and lowercase: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
abc = string.lowercase + string.uppercase
## Looping each letter of the received text
for letter in text:
## If the current letter of the loop exists in our abc variable contents, it means it's a letter and not a symbol or space
## So we can apply upper() or lower() to the letter.
if letter in abc:
## If the letter is currently uppercase, then we turn it into lowercase
if letter.isupper():
results.append(letter.lower())
## If the letter is currently lowercase, then we turn it into uppercase
else:
results.append(letter.upper())
## The current letter of the loop is not in our abc variable so it could be anything but a letter
## So we just append it to our results list
else:
results.append(letter)
## Once the loop finishes we just join every item in the list to make the final string and return it
return ''.join(results)
print invertCase('SoMeOnE Is hAvING fUN')
Output:
sOmEoNe iS HaVing Fun
The variable i is already a 1 character string because the for loop processes strings this way. Also, when you call str[i].upper(), it needs to either be assigned to something, or printed out, otherwise the character is never actually changed in place. .lower() and .upper() also have a behaviour which already checks the range for you, and returns the same characters. Eg. if it already uppercase, or a number, upper() will just return the same character.
Your function can be simplified as follows:
import sys
def CapsChanger(str):
for i in str:
sys.stdout.write (i.lower() if (i.upper() == i) else i.upper())
print
str = raw_input()
CapsChanger(str)
sys.stdout.write is used to avoid printing out extra spaces. The ternary operator is used to switch case in one shot:
<value1> if <condition> else <value2>
i is a string, not index. If You need index use enumerate:
for idx, i in str:
print idx, i
Insted of ord(chr) use string that represent a letter.
Insted of two if conditions use Chained Comparisons.
def CapsChanger(str):
out = []
for idx,chr in enumerate(str):
if 'Z' >= chr >= 'A':
out.append(chr.lower())
elif 'z' >= chr >= 'a':
out.append(chr.upper())
print(''.join(out))

Count vowels from raw input

I have a homework question which asks to read a string through raw input and count how many vowels are in the string. This is what I have so far but I have encountered a problem:
def vowels():
vowels = ["a","e","i","o","u"]
count = 0
string = raw_input ("Enter a string: ")
for i in range(0, len(string)):
if string[i] == vowels[i]:
count = count+1
print count
vowels()
It counts the vowels fine, but due to if string[i] == vowels[i]:, it will only count one vowel once as i keeps increasing in the range. How can I change this code to check the inputted string for vowels without encountering this problem?
in operator
You probably want to use the in operator instead of the == operator - the in operator lets you check to see if a particular item is in a sequence/set.
1 in [1,2,3] # True
1 in [2,3,4] # False
'a' in ['a','e','i','o','u'] # True
'a' in 'aeiou' # Also True
Some other comments:
Sets
The in operator is most efficient when used with a set, which is a data type specifically designed to be quick for "is item X part of this set of items" kind of operations.*
vowels = set(['a','e','i','o','u'])
*dicts are also efficient with in, which checks to see if a key exists in the dict.
Iterating on strings
A string is a sequence type in Python, which means that you don't need to go to all of the effort of getting the length and then using indices - you can just iterate over the string and you'll get each character in turn:
E.g.:
for character in my_string:
if character in vowels:
# ...
Initializing a set with a string
Above, you may have noticed that creating a set with pre-set values (at least in Python 2.x) involves using a list. This is because the set() type constructor takes a sequence of items. You may also notice that in the previous section, I mentioned that strings are sequences in Python - sequences of characters.
What this means is that if you want a set of characters, you can actually just pass a string of those characters to the set() constructor - you don't need to have a list one single-character strings. In other words, the following two lines are equivalent:
set_from_string = set('aeiou')
set_from_list = set(['a','e','i','o','u'])
Neat, huh? :) Do note, however, that this can also bite you if you're trying to make a set of strings, rather than a set of characters. For instance, the following two lines are not the same:
set_with_one_string = set(['cat'])
set_with_three_characters = set('cat')
The former is a set with one element:
'cat' in set_with_one_string # True
'c' in set_with_one_string # False
Whereas the latter is a set with three elements (each one a character):
'c' in set_with_three_characters` # True
'cat' in set_with_three_characters # False
Case sensitivity
Comparing characters is case sensitive. 'a' == 'A' is False, as is 'A' in 'aeiou'. To get around this, you can transform your input to match the case of what you're comparing against:
lowercase_string = input_string.lower()
You can simplify this code:
def vowels():
vowels = 'aeiou'
count = 0
string = raw_input ("Enter a string: ")
for i in string:
if i in vowels:
count += 1
print count
Strings are iterable in Python.
for i in range(0, len(string)):
if string[i] == vowels[i]:
This actually has a subtler problem than only counting each vowel once - it actually only tests if the first letter of the string is exactly a, if the second is exactly e and so on.. until you get past the fifth. It will try to test string[5] == vowels[5] - which gives an error.
You don't want to use i to look into vowels, you want a nested loop with a second index that will make sense for vowels - eg,
for i in range(len(string)):
for j in range(len(vowels)):
if string[i] == vowels[j]:
count += 1
This can be simplified further by realising that, in Python, you very rarely want to iterate over the indexes into a sequence - the for loop knows how to iterate over everything that you can do string[0], string[1] and so on, giving:
for s in string:
for v in vowels:
if s == v:
count += 1
The inner loop can be simplified using the in operation on lists - it does exactly the same thing as this code, but it keeps your code's logic at a higher level (what you want to do vs. how to do it):
for s in string:
if s in vowels:
count += 1
Now, it turns out that Python lets do math with booleans (which is what s in vowels gives you) and ints - True behaves as 1, False as 0, so True + True + False is 2. This leads to a one liner using a generator expression and sum:
sum(s in vowels for s in string)
Which reads as 'for every character in string, count how many are in vowels'.
you can use filter for a one liner
print len(filter(lambda ch:ch.lower() in "aeiou","This is a String"))
Here's a more condensed version using sum with a generator:
def vowels():
string = raw_input("Enter a string: ")
print sum(1 for x in string if x.lower() in 'aeiou')
vowels()
Option on a theme
Mystring = "The lazy DOG jumped Over"
Usestring = ""
count=0
for i in Mystring:
if i.lower() in 'aeiou':
count +=1
Usestring +='^'
else:
Usestring +=' '
print (Mystring+'\n'+Usestring)
print ('Vowels =',count)
The lazy DOG jumped Over
^ ^ ^ ^ ^ ^ ^
Vowels = 7

Categories

Resources