Python: How to print results from conditions all in one line [duplicate] - python

This question already has answers here:
How can I print multiple things on the same line, one at a time?
(18 answers)
Closed last month.
I'm new to coding, and I found this exercise problem in a Python practice website. The instructions go like this:
"Write a function translate() that will translate a text into "rövarspråket" (Swedish for "robber's language"). That is, double every consonant and place an occurrence of "o" in between. For example, translate("this is fun") should return the string "tothohisos isos fofunon".
So I inputted this code:
def translate(string):
vowels=['a','e','i','o','u']
for letter in string:
if letter in vowels:
print(letter)
else:
print(letter+'o'+letter)
print(translate('this is fun'))
and I got this:
tot
hoh
i
sos
o
i
sos
o
fof
u
non
None
So how do I put all these strings in one line? I've been scratching my head for so long. Please help and thank you:)

You can concatenate the strings iteratively. You should include a whitespace as part of the characters to exclude to avoid putting an 'o' in between whitespaces.
def translate(string):
notconsonant = ['a','e','i','o','u', ' ']
s = ''
for letter in string:
if letter in notconsonant:
s += letter
else:
s += letter+'o'+letter
return s
Or use join with a generator expression that returns the right letter combination via a ternary operator:
def translate(string):
notconsonant = {'a','e','i','o','u', ' '}
return ''.join(letter if letter in notconsonant else letter+'o'+letter for letter in string)
Note that you can speed up the lookup of letters that are not consonants if you made the list a set, as membership check for sets is relatively faster.
>>> translate('this is fun')
'tothohisos isos fofunon'

Just use the end parameter in print function. (I assumed that you are using python 3.x, with print being a function)
def translate(string):
vowels=['a','e','i','o','u']
for letter in string:
if letter in vowels:
print(letter, end='')
else:
print(letter+'o'+letter, end='')
print(translate('this is fun'))

Try to append it in a temporary string and to print it at the end ;)

print get's you to a new line. Use a concatenation and a new string instead (here the new string is called result) :
def translate(string):
vowels=['a','e','i','o','u']
# Use a new variable :
result = ''
for letter in string:
if letter in vowels:
result = result + letter
else:
result = result + letter + 'o' + letter
return result
print(translate('this is fun'))

Related

How can I replace every letter in a string with something else? (Python 3) [duplicate]

This question already has answers here:
replace all characters in a string with asterisks
(4 answers)
Closed 2 years ago.
I have to develop a hangman game as part of a school assignment, and I'm trying to create a new string that will output the word to be guessed as just stars. e.g hello would be ****. Below is the code I have tried, the output seems to be only the last letter of the string to be replaced with a star, but the rest of the string is seemingly untouched:
word_to_guess = input("Enter a word for player 2 to guess:")
def guess_the_word(word_to_guess):
for letter in word_to_guess:
number_of_letters = word_to_guess.replace(letter, '*') #Taking the original string and replacing each letter with a star, giving player 2 an indicator of how many letters there are to guess
print("{} is the word for today".format(number_of_letters))
Any pointers as to where I went wrong will be appreciated
Just try
'*' * len(word_to_guess)
which will multiply the * with the length of word_to_guess.
You are reassigning the output of word_to_guess.replace, so each time it's for a single operation:
word = 'hello'
output = word.replace('h', '*')
# *ello
output = word.replace('e', '*')
# h*llo
# and so on
You probably just need
def guess_the_word(word):
letters = ''
for char in word:
letters += '*'
print(letters)
Or
def word_to_guess(word):
return ''.join('*' for char in word)
A better way to get a hashed version the same length as the word may be by using the length property.
Example:
word = "sponge"
hashedWord = ''
hashedWord += '#'*len(word)
print(f"Hashed word: {hashedWord}")
Output:
Hashed word: ######

How can I get the index of a recurring character from a string?

I'm working with a hangman like project whereas if the user inputs a letter and matches with the solution, it replaces a specific asterisk that corresponds to the position of the letter in the solution. I'm trying to do this by getting the index of the instance of that letter in the solution then replacing the the matching index in the asterisk.
The thing here is that I only get the first instance of a recurring character when I used var.index(character) whereas I also have to replace the other instance of that letter. Here's the code:
word = 'turtlet'
astk = '******'
for i in word:
if i == t:
astk[word.index('i')] = i
Here it just replaces the first instance of 't' every time. How can I possibly solve this?
index() gives you only the index of the first occurrence of the character (technically, substring) in a string. You should take advantage of using enumerate(). Also, instead of a string, your guess (hidden word) should be a list, since strings are immutable and do not support item assignment, which means you cannot reveal the character if the user's guess was correct. You can then join() it when you want to display it. Here is a very simplified version of the game so you can see it in action:
word = 'turtlet'
guess = ['*'] * len(word)
while '*' in guess:
print(''.join(guess))
char = input('Enter char: ')
for i, x in enumerate(word):
if x == char:
guess[i] = char
print(''.join(guess))
print('Finished!')
Note the the find method of the string type has an optional parameter that tells where to start the search. So if you are sure that the string word has at least two ts, you can use
firstindex = word.find('t')
secondindex = word.find('t', firstindex + 1)
I'm sure you can see how to adapt that to other uses.
I believe there's a better way to do your specific task.
Simply keep the word (or phrase) itself and, when you need to display the masked phrase, calculate it at that point. The following snippet shows how you can do this:
>>> import re
>>> phrase = 'My hovercraft is full of eels'
>>> letters = ' mefl'
>>> display = re.sub("[^"+letters+"]", '*', phrase, flags=re.IGNORECASE)
>>> display
'M* ***e****f* ** f*ll *f eel*'
Note that letters should start with the characters you want displayed regardless (space in my case but may include punctuation as well). As each letter is guessed, add it to letters and recalculate/redisplay the masked phrase.
The regular expression substitution replaces all characters that are not in letters, with an asterisk.
for i in range(len(word)):
if word[i] == "t":
astk = astk[:i] + word[i] + astk[i + 1:]

python - replace string with condition yields weird result

I wrote a function that replace the letter if the letter is the same as the next letter in the string:
word = 'abcdeefghiijkl'
def replace_letter(word):
for i in range(len(word)-1):
if word[i] == word[i+1]:
word = word.replace(word[i],'7')
return word
replace_letter(word)
This should give me 'abcd7efgh7ijkl', but I got 'abcd77fgh77jkl'. Once the letter is the same with the next one both are replaced with '7'.
Why?
You should use:
word = word.replace(word[i],'7', 1)
to indicate that you want to make one character replacement. Calling replace() without indicating how many replacements you wish to make will replace any occurrence of the character "e" (as found at word[i]) by "7".
the answer above has a little bug
for example:
when your word = 'ebcdeefghiijkl'
the result of replace_letter(word) will be '7abcdeefgh7ijkl'
you can try this:
def replace_letter(word):
result=[]
for i in range(len(word)):
if i!=len(word)-1 and word[i] == word[i+1]:
result.append('7')
else:
result.append(word[i])
return ''.join(result)

word separator for python coding [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
So the question reads:
Write a program that accepts as input a sentence in which all of the words are run together but the first character of each word is uppercase. Convert the sentence to a string in which the words are separated by spaces and only the first word starts with an uppercase letter. For example the string "StopAndSmellTheRoses." would be converted to " Stop and smell the roses."
I am so confused this my code so far.
def main():
#User enters a sentence
my_string=input('enter a sentence: ')
print(my_string.capitalize())
main()
You can loop through the string and add a character each time to a result:
my_string = "StopAndSmellTheRoses"
i = 0
result = ""
for c in my_string:
if c.isupper() and i > 0:
result += " "
result += c.lower()
else:
result += c
i += 1
print result
We'll use c for each character as we walk through the string and we'll use i to keep track of the position in the string.
There are two possibilities: it's either an uppercase character (excluding the first one) or it's not.
In the first case we'll add a space and that character as lowercase to the result. This ensures a space is inserted before each uppercase character further in the sentence.
In the second case it's a lowercase character or the uppercase character at the beginning of the sentence. We don't have to do anything with these and we'll add it right away.
Lastly we add one to i whenever we're done with a character (i += 1) as this means we correctly know where we are in the sentence.
Welcome to SO!
One way to do this is to loop through your string, checking the chars one by one:
#You've learned how to iterate through something, right?
i = 0 #a counter
for c in my_string: #get the characters of my_string, one by one.
if c.isupper(): #check if it's in upper case
if i == 0: #if it's the first letter
new_string += c #let it be like the original
else:
new_string += ' '+.lower() #it's not the first letter,
#so add space, and lower the letter.
else:
new_string += c #else, only add the letter to the new string
i += 1
Edit added a double-check to see if it's the first letter of the sentence or not. Updated demo.
As an alternative to using a counter, you can also use the built-in function enumerate, which returns a tuple of index and values.
for i,c in enumerate(my_string): #get the characters of my_string, one by one.
if c.isupper(): #check if it's in upper case
if i == 0: #if it's the first letter
new_string += c #let it be like the original
else:
new_string += ' '+c.lower() #it's not the first letter,
#so add space, and lower the letter.
else:
new_string += c #else, only add the letter to the new string
Demo
>>> my_string = 'ImCool'
>>> new_string = ''
>>> i = 0 #a counter
>>> for c in my_string: #get the characters of my_string, one by one.
if c.isupper(): #check if it's in upper case
if i == 0: #if it's the first letter
new_string += c #let it be like the original
else:
new_string += ' '+.lower() #it's not the first letter,
#so add space, and lower the letter.
else:
new_string += c #else, only add the letter to the new string
i += 1
>>> new_string
'Im cool'
Hope this helps!
You'll need a bit of regex.
import re
split = re.findall(r'[A-Z][a-z\.]+', 'HelloThisIsMyString.')
You'll also need to join those together (inserting spaces)
' '.join(...)
and handle case conversions
' '.join(word.lower() for word in split)
(and as you already did, capitalize the first word)
' '.join(word.lower() for word in split).capitalize()
It appears that you are a little confused and this is to be expected if you are new to Python. I'm assuming you take input from the user as opposed to input for a function. Either way I would create a simple function that you could insert the users input into. The function below will accomplish what the problem asks.
def sentenceSplitter(sentence):
result = ""
for i, x in enumerate(sentence): #i is character index, x is the element
if i == 0:
result = result + x
elif x.isupper() == False: #if element is not uppercase, add it to the result
result = result + x
else: # Otherwise, add a space and lowercase the next letter
result = result + " " +x.lower()
return(result)
To reiterate, if you are looking to print out the sentence you would write this after the function:
def main():
#User enters a sentence
my_string=input('enter a sentence: ')
print(sentenceSplitter(my_string))
main()
If you are still confused feel free to ask any further questions.

Remove whitespace in for loop

I've made a simple script in python which shifts the letters up 5 spaces in the ASCII table using chr and ord. See below:
word = "python"
print 'Shifted 5 letters are: '
for letters in word:
print chr(ord(letters)+5),
The output is:
Shifted 5 letters is:
u ~ y m t s
The output is great, but how do I stop the for loop putting spaces in-between each letter?
If you don't need to use the for loop, simply do this:
print ''.join([chr(ord(letter) + 5) for letter in word])
instead of the whole loop.
There is no way to stop Python 2.x's print statement from printing a space when you use the "magic comma".
This is part of the reason Python 3.x's print function is more flexible, using keyword arguments instead of magic syntax:
for letters in word:
print(chr(ord(letters)+5), end='')
If you really want to, you can get the same behavior in Python 2.x with from __future__ import print_function (or by using the third-party six library).
However, usually, when you're having problem fighting with print to do what you want, the solution is to format your string first, then print it. So:
output = ''
for letters in word:
output += chr(ord(letters)+5)
print output
It's generally more pythonic (and faster) to build up a list of strings, and calling join at the end, instead of repeatedly appending to a string:
output = []
for letters in word:
output.append(chr(ord(letters)+5))
print ''.join(output)
And you can make that simpler (and even more fasterer) by turning the loop into a comprehension instead of a statement:
print ''.join(chr(ord(letters) + 5) for letters in word)
I don't know if I get what you're asking 100 % but this work-around returned the letters without any whitespace :
def no_space(word) :
new_word = ""
for letter in word :
new_word += chr(ord(letter) + 5)
return new_word
Then call the function :
no_space("python")
Result : 'u~ymts'

Categories

Resources