Printing Out Every Third Letter Python - python

I'm using Grok Learning and the task it give you is 'to select every third letter out of a sentence (starting from the first letter), and print out those letters with spaces in between them.'
This is my code:
text = input("Message? ")
length = len(text)
for i in range (0, length, 3):
decoded = text[i]
print(decoded, end=" ")
Although I it says it isn't correct, it say this is the desired out-put:
Message? cxohawalkldflghemwnsegfaeap
c h a l l e n g e
And my output is the same expect, in my output, I have a space after the last 'e' in challenge. Can anyone think of a way to fix this?

To have spaces only between the characters, you could use a slice to create the string "challenge" then use str.join to add the spaces:
" ".join(text[::3])

Here's Grok's explanation to your question: "So, this question is asking you to loop over a string, and print out every third letter. The easiest way to do this is to use for and range, letting range do all the heavy lifting and hard work! We know that range creates a list of numbers, - we can use these numbers as indexes for the message!"
So if you are going to include functions like print, len, end, range, input, for and in functions, your code should look somewhat similar to this:
line = input('Message? ')
result = line[0]
for i in range(3, len(line), 3):
result += ' ' + line[i]
print(result)
Or this:
line = input('Message? ')
print(line[0], end='')
for i in range(3, len(line), 3):
print(' ' + line[i], end='')
print()
Or maybe this:
code = input ('Message? ') [0::3]
msg = ""
for i in code: msg += " " + i
print (msg [1:])
All of these should work, and I hope this answers your question.

I think Grok is just really picky about the details. (It's also case sensitive)
Maybe try this for an alternative because this one worked for me:
message = input('Message? ')
last_index = len(message) -1
decoded = ''
for i in range(0, last_index, 3):
decoded += message[i] + ' '
print(decoded.rstrip())

You should take another look at the notes on this page about building up a string, and then printing it out all at once, in this case perhaps using rstrip() or output[:-1] to leave off the space on the far right.
Here's an example printing out the numbers 0 to 9 in the same fashion, using both rstrip and slicing.
output = ""
for i in range(10):
output = output + str(i) + ' '
print(output[:-1])
print(output.rstrip())

If you look through the Grok course, there is one page called ‘Step by step, side by side’ (link here at https://groklearning.com/learn/intro-python-1/repeating-things/8/) where it introduces the rstrip function. If you write print(output.rstrip()) it will get rid of whitespace to the right of the string.

Related

How would I execute this? Python

I am pretty new to python and would like to know how to write a program that asks the user to enter a string that contains the letter "a". Then, on the first line, the program should print the part of the string up to and including the certain letter, and on the second line should be the rest of the string.
For example...
Enter a word: Buffalo
Buffa
lo
This is what I have so far :
text = raw_input("Type something: ")
left_text = text.partition("a")[0]
print left_text
So, I have figured out the first part of printing the string all the way up to the certain letter but then don't know how to print the remaining part of the string.
Any help would be appreciated
If what you want is the first occurrence of a certain character, you can use str.find for that. Then, just cur the string into two pieces based on that index!
In python 3:
split_char = 'a'
text = input()
index = text.find(split_char)
left = text[:-index]
right = text[-index:]
print(left, '\n', right)
I don't have a python2 on hand to make sure, but I assume this should work on python 2:
split_char = 'a'
text = raw_input()
index = text.find(split_char)
left = text[:-index]
right = text[-index:]
print left + '\n' + right)
Another option that is far more concise is to use
left_text, sep, right_text = text.partition("a")
print (left_text + sep, '\n', right_text)
and then as suggested in the comments, thanks #AChampion !
You should have some knowledge about slicing and concatenating string or list. You can learn them here Slicing and Concatenating
word = raw_input('Enter word:') # raw_input in python 2.x and input in python 3.x
split_word = raw_input('Split at: ')
splitting = word.partition(split_word)
'''Here lets assume,
word = 'buffalo'
split_word = 'a'
Then, splitting variable returns list, storing three value,
['buff', 'a', 'lo']
To get your desire output you need to do some slicing and concatenate some value .
'''
output = '{}\n{}'.join(splitting[0] + splitting[1], splitting[2])
print(output)
First find the indices of the character in the given string, then print the string accordingly using the indices.
Python 3
string=input("Enter string")
def find(s, ch):
return [i for i, ltr in enumerate(s) if ltr == ch]
indices=find(string, "a")
for index in indices[::-1]:
print(string[:index+1])
print(string[indices[-1]+1:])

Cleaning up a string without split/strip/built-in functions

My requirements
Use Python to create a function cleanstring(S) to "clean up" the spaces in a sentence S.
The sentence may have extra spaces at the front and/or at the end and/or between words.
The subroutine returns a new version of the sentence without the extra spaces.
That is, in the new string, the words should be the same but there should be no spaces at the start, only one space between each word and no spaces at the end.
This program is about you writing code to search through a string to find words and so you are not allowed to use the split function in Python.
You can solve this problem with the basic capabilities of the if and while statements and string operations of len and concatentation.
For example: if the input is: " Hello to the world !" then the output should be: "Hello to the world!"
Question
My program deletes more characters in the program than needed.
Input: " Hello World ! "
Output: "HellWorl"
How do I fix the error in my program?
def cleanupstring (S):
newstring = ["", 0]
j = 1
for i in range(len(S) - 1):
if S[i] != " " and S[i+1] != " ":
newstring[0] = newstring[0] + S[i]
else:
newstring[1] = newstring [1] + 1
return newstring
# main program
sentence = input("Enter a string: ")
outputList = cleanupstring(sentence)
print("A total of", outputList[1], "characters have been removed from your
string.")
print("The new string is:", outputList[0])
Welcome to Stackoverflow. When I started reading I though this was going to be a "please answer my homework" question, but you've actually made a pretty fair effort at solving the problem, so I'm happy to try and help (only you can say whether I actually do).
It's sometimes difficult when you are learning a new language to drop techniques that are much more appropriate in other languages. Doing it character by character you normally just use for c in s rather than incrementing index values like you would in C (though either approach works, index incrementation where not necessary is sometimes regarded as "unpythonic"). Your basic idea seems to be to detect a space followed by another space, otherwise copying characters from the input to the output.
The logic can be simplified by retaining the last character you sent to the output. If it's a space, don't send any more spaces. A loop at the front gets rid of any leading spaces, and since there can be at most one space at the end it can be eliminated easily if present.
I'm not sure why you use a list to keep your results in, as it makes the code much more difficult to understand. If you need to return multiple pieces of information it's much easier to compute them in individual variables and then construct the result in the return statement.
So one desirable modification would be to replace newstring[0] with, say, out_s and newstring[1] with, say count. That will make it a bit clearer what's going on. Then at the end return [out_s, count] if you really need a list. A tuple using return out_s, count would be more usual.
def cleanupstring (s):
out_s = ''
count = 0
last_out = ' '
for c in s:
if c != ' ' or last_out != ' ':
last_out = c
out_s += c
else:
count += 1
if last_out == ' ':
count -= 1
out_s = out_s[:-1]
return out_s, count
# main program
sentence = input("Enter a string: ")
outputList = cleanupstring(sentence)
print("A total of", outputList[1], "characters have been removed from your string.")
print("The new string is:", outputList[0])
Sometimes you just don't have certain pieces of information that would help you to answer the question extremely succinctly. You most likely haven't yet been taught about the strip and replace methods, and so I imagine the following (untested) code
def cleanupstring(s):
out_s = s
while ' ' in out_s:
out_s = out_s.strip().replace(' ', ' ')
return out_s, len(s)-len(out_s)
would be right out.
Also, you can use an "unpacking assignment" to bind the different elements of the function's output directly to names by writing
s, c = cleanupstring(...)
I'm sure you will agree that
print("A total of", c, "characters have been removed from your string.")
print("The new string is:", s)
is rather easier to read. Python values readability so highly because with readable code it's easier to understand the intent of the author. If your code is hard to understand there's a good chance you still have some refactoring to do!
If the "space" it's literally spaces rather than whitespace then the following would work:
import re
def clean_string(value):
return re.sub('[ ]{2,}', ' ', value.strip())
If the stripped values contains consecutive spaces then replace with one space.
My approach would be to keep the last character available and make the decision whether it is a space or not:
def cleanupstring (S):
newstring = ["", 0]
last_character = ' ' # catch initial spaces
for i in range(len(S)-1):
char = S[i]
if char is ' ' and last_character is ' ':
continue # ignore
else:
last_character = char
newstring [0] = newstring[0] + char
return newstring

How do I make it so the code only shifts the letters and not the space?

#get string and shift from user
string = input('Please enter a string to be ciphered: ')
shift = input('Please enter a shift amount between 0 and 25: ')
#strings are immutable so it must be converted to a list
s=list(string)
#now this will convert each character based on the shift
for i in range(0,len(s)):
s[i]=chr(ord(s[i]) + int(shift))
print ("".join(s))
You should call the method str.alpha to ensure that the chosen element is an alphabet before shifting
for i in range(0,len(s)):
if elem.isaplha():
s[i]=chr(ord(s[i]) + int(shift))
On a second though, you are doing to much work here. Why not use a comprehension expression?
s = ''.join(chr(ord(elem) + shift) if elem.isalpha() else elem for elem in s)
or if you are adventurous enough
s = ''.join([elem, chr(ord(elem) + shift)][elem.isalpha()] for elem in s)
and finally have you checked the string.makestrans along with str.translate to do the conversion?
from string import maketrans, ascii_alpha
s = s.translate(maketrans(ascii_alpha[shift:] + string.ascii_alpha[:shift])
All you have to do is check if the current character is not one you want to skip.
for i in range(0,len(s)):
#If not a space, cipher this character.
if s[i] != ' ':
s[i]=chr(ord(s[i]) + int(shift))
There is however, a possibility that one of your characters will be ciphered to a space, in which case that character would be skipped when reversing the cipher.
Also, a simple cipher like this should not be considered secure in the least.

Python Printing and multiplying strings in Print statement

I am trying to write a simple python program that prints two ##, then # #, and increases the number of spaces in between the #'s each time. Here is the code I tried:
i=0
while (i<=5):
print ("#" (" " * i) "#")
#print (" " * i)
#print ("#" "#")
The multiplication works in the first line of code I tested then commended out, I see it in the shell each time it prints one more space.
Printing two #'s works also.
I can't figure out how to combine it into one statement that works, or any other method of doing this.
Any help would be appreciated, thanks.
i=0
while (i<=5):
print( "#" +(" "*i)+ "#")
i=i+1
You need to add the strings inside the print statement and increment i.
You want to print a string that depends an a variable. There are other methods to build a string but the simplest, most obvious one is adding together some fixed pieces and some computed pieces, in your case a "#", a sequence of spaces and another "#". To add together the pieces you have to use the + operator, like in "#"+" "+"#".
Another problem in your code is the while loop, if you don't increment the variable i its value will be always 0 and the loop will be executed forever!
Eventually you will learn that the idiom to iterate over a sequence of integers, from 0 to n-1 is for i in range(n): ..., but for now the while loop is good enough.
This should do it:
i=0
while (i<=5):
print ('#' + i * ' ' + '#')
i = i + 1
Try this:
def test(self, number: int):
for i in range (number)):
print('#' +i * ''+ '#')
i+=1
return

Advice on python program

So i had to write a program that asks for a user input (which should be a 3 letter string) and it outputs the six permutations of the variations of the placements of the letters inside the string. However, my professor wants the output to be surrounded by curly brackets whereas mine is a list (so it is square brackets). How do i fix this? Also, how do I check if none of the letters in the input repeat so that the main program keeps asking the user to enter input and check it for error?
Thank you
The only datatype im aware of that 'natively' outputs with { } is a dictionary, which doesnt seem to apply here. I would just write a small function to output your lists in the desired fashion
>>> def curlyBracketOutput(l):
x = ''
for i in l: x += i
return '{' + x + '}'
>>> curlyBracketOutput(['a','b','c'])
'{abc}'
ok, for one thing, as everyone here has said, print '{'. other than that, you can use the following code in your script to check for repeated words,
letterlist = []
def takeInput(string):
for x in string:
if x not in letterlist:
letterlist.append(x)
else:
return 0
return 1
then as for your asking for input and checking for errors, you can do that by,
while(True): #or any other condition
string = input("Enter 3 letter string")
if len(string)!=3:
print("String size inadequate")
continue
if takeInput(string):
arraylist = permutation(string) #--call permutation method here
#then iterate the permutations and print them in {}
for x in arraylist: print("{" + x + "}")
else:
print("At least one of the letters already used")
The answer to both question is to use a loop.
Print the "{" and then loop through all the elements printing them.
But the input inside a loop and keep looping until you get what you want.
Curly brackets refers to a dict?
I think a
list(set(the_input))
should give you a list of unique letters. to check if they occur more than once
and
theinput.count(one_letter) > 1
should tell you if there is mor than one.
>>> chars = ['a','b','c']
>>> def Output(chars):
... return "{%s}" % ''.join(chars)
...
>>> print Output(chars)
{abc}
>>>
Or just do something tremendously kludgy:
print repr(YourExistingOutput).replace("[", "{").replace("]", "}")

Categories