word separator for python coding [closed] - python

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.

Related

How do you split duplicate letters with "x" in Python?

I am trying to create a function which is able to detect when two letters back to back are duplicates, for example the ls in "hello", and split the duplicate letters with the letter "x". Here is my code:
plaintext = input("Enter plaintext here: ")
plaintext = plaintext.lower() # makes plaintext lowercase
plaintext = plaintext.replace(" ", "") # removes all spaces
# this separates all duplicate letters
i = 0 # sets i to 0
for letter in plaintext:
if plaintext[-1] == plaintext[-2]: # if the last letter is the same as the second to last
plaintext = plaintext[:-1] + "x" + plaintext[-1:] # separate them with an x
elif plaintext[i] == plaintext [i+1]: # if one letter is the same as the next letter
# the line above makes an error
plaintext = plaintext[:i+1] + "x" + plaintext[i+1:] #separate them with an x
i += 1
else:
i += 1
This code works when I enter hello there as the input; I receive helxlothere. However, when I test another input, such as heythere, IndexError: string index out of range shows up for elif line (line 12). How can I make this code work for all inputs?
You can use regex to achieve this.
For both approaches, it will work for hello there hey there
The difference comes when more than two character repetition happens.
approach 1
import re
string='hello there'
# find Any repeated character and add x in between them
answer = re.sub(r'(.)\1{1}', r'\1x\1', string)
print(answer)
Here for hellllo there text, you will get output helxllxlo there
approach 2
alternatively, you can use this method.
s="hello there"
for match in re.finditer(r"(.)\1+", s):
old=s[match.start():match.end()]
s=s.replace(old,'x'.join(old))
print(s)
here for hellllo there text, you will get output helxlxlxlo there as output.
I think the second approach will be more appropriate.
The IndexError is caused by the fact that you are looking at plaintext[i+1]. As you can see in the word heythere, there are no letters which match back to back, and therefore the code continues until it hits the end, and so you get an IndexError because there is no element i+1.
You can fix this by using this code instead:
plaintext = input("Enter plaintext here: ")
plaintext = plaintext.lower() # makes plaintext lowercase
plaintext = plaintext.replace(" ", "") # removes all spaces
# this separates all duplicate letters
i = 0 # sets i to 0
for letter in plaintext:
if plaintext[-1] == plaintext[-2]: # if the last letter is the same as the second to last
plaintext = plaintext[:-1] + "x" + plaintext[-1:] # separate them with an x
try:
elif plaintext[i] == plaintext [i+1]: # if one letter is the same as the next letter
# the line above makes an error
plaintext = plaintext[:i+1] + "x" + plaintext[i+1:] #separate them with an x
i += 1
else:
i += 1
except IndexError:
pass
This code should stop your code from crashing in the elif statement, while also completing properly.
Hope this helps, have a nice day!
You are receiving the IndexError because during iterating, when the loop reaches the last letter,
elif plaintext[i] == plaintext [i+1]:
this line checks for the letter after the last letter, which does not exist, which causes the program to run into IndexError.
You have to check till the second last letter, for it to work properly.
A simple and easier way to arrive at the same output with a bit easier logic.
Logic
Create a new string and insert all letters which are in the old string, plaintext, to the new string, newPlainText, and check only for one condition that is whether the last letter is same as current or not and if yes then also insert letter 'x' into the newPlainText and that's it!
plaintext = input("Enter plaintext here: ")
plaintext = plaintext.lower() # makes plaintext lowercase
plaintext = plaintext.replace(" ", "") # removes all spaces
# this separates all duplicate letters
newPlainText = plaintext[0] # copy the first letter of plaintext to the new string which will handle the duplicates and insert `x` between them
i = 1 # sets i to 1
while i < len(plaintext):
if plaintext[i] == plaintext[i-1]: # we check that if prev and current letters are same then also append x to the new string
newPlainText += "x"
newPlainText += plaintext[i] # we insert the required current letter to the new string in each iteration
i += 1
print(newPlainText)

Trying to allow user to use either capital or lowercase letters in Hangman code

I'm writing a hangman game in python for class. The user is told they have guessed incorrectly when they put a lower case when it is upper case and vice versa. Also when there is a space in the input it displays as an underscore (_) as well.
def gettingWord(theWord, lettersGuessed):
count = 0
blank = ['_ '] * len(theWord)
for i, c in enumerate(theWord):
if c in lettersGuessed:
count = count + 1
blank.insert(count-1,c)
blank.pop(count)
if count == len(theWord):
return ''.join(str(e) for e in blank)
else:
count = count + 1
blank.insert(count-1,'_')
blank.pop(count)
if count == len(theWord):
return ''.join(str(e) for e in blank)
The code itself works I just want to know how I can fix this issue. Can anyone help?
If I'm understanding correctly you want the user to be able to use uppercase and lowercase characters without affecting the result. If that's the case then you can use string's method lower() in order to turn each character the user guesses lowercase. In your function you could just add these two lines in the beginning:
theWord = theWord.lower()
lettersGuessed = [c.lower() for c in lettersGuessed]
First you turn the word to guess into lowercase, and then you turn each character in lettersGuessed lowercase (assuming lettersGuessed is a list of characters, if it's a string then you can just write lettersGuessed = lettersGuessed.lower()). This way all characters will be lowercase so the answer will depend on the character only and not on the casing.
Convert both the character and the letters guessed to lowercase to ignore case. If the character is whitespace, you also want to insert the character so you should add or not c.strip() to the if check to also insert the character if its whitespace.
Also, just to reduce code duplication, you should try and remove the duplicate code out of the if/else blocks, this will help with maintaining this or changing the logic in the future.
def gettingWord(theWord, lettersGuessed):
count = 0
blank = ['_ '] * len(theWord)
for c in theWord:
if c.lower() in lettersGuessed.lower() or not c.strip():
blank.insert(count, c)
else:
blank.insert(count, '_')
count = count + 1
blank.pop(count)
if count == len(theWord):
return ''.join(str(e) for e in blank)
Convert everything to lowercase, and strip spaces.
All the words in the word bank should be lowercase
When getting input:
letter = input('Enter a letter: ').lower().strip()
That should fix your problems with spaces and casing.

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: How to print results from conditions all in one line [duplicate]

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'))

Implementing a hangman function in Python

Here is the problematic piece of my function:
def hangman1(word):
global guessesMade
global guessesLeft
currentGuess = '_ ' * len(word)
let = print(input('Please guess a letter: '))
for i in range(len(word)):
if word[i] == let:
print('{} is contained in the word.'.format(let))
if i == 0:
currentGuess = word[0] + currentGuess[1:]
else:
currentGuess = currentGuess[:i] + word[i] + currentGuess[i + 1:]
print(currentGuess)
The user enters a letter at the prompt and it checks if the letter is in the randomWord that was generated outside of the function from a list of words. I can get it to print the blanks correctly, but if the user enters a letter that is in the word it prints out a line of the correct letter instead of the blanks with the correct letter mixed in between.
Any help is appreciated.
The main problem you're having right now is two-fold - one, that the replace() method replaces all instances of any given input within a string, not the first one, and two, that you don't currently have any way of telling which letters you've already uncovered. Calling replace("_", let) will always replace every single instance of "_", and given that you're applying that to a string that is only composed of underscores, it'll always overwrite the entire string. It seems like you're also regenerating hidden_let every time hangman() is called with a guess letter, meaning that best-case with your design now you're only going to ever show every letter the user just guessed and a bunch of underscores otherwise.
What you'd want to do is have two values, correct_word and current_guess. correct_word will be the word the player has to guess, and current_guess will be their progress in guessing the word, starting with a string of only underscores of the same length as correct_word.
Here's a short example. I've taken the liberty of removing your global references - globals are generally frowned upon - and encapsulated the behavior in a small class. You'd want to replace the value in hangmanner.play_hangman() with whatever your random word is.
class Hangmanner:
correct_word = ''
current_guess = ''
def play_hangman(self, word):
self.correct_word = word
self.current_guess = '_' * len(self.correct_word)
while self.current_guess != self.correct_word:
self.guess_letter(input("Please guess a letter: "))
def guess_letter(self, guessed_letter):
for i in range(len(self.correct_word)):
if self.correct_word[i] == guessed_letter:
if i == 0:
self.current_guess = self.correct_word[i] + self.current_guess[1:]
else:
self.current_guess = self.current_guess[:i] + self.correct_word[i] + self.current_guess[i + 1:]
print(self.current_guess)
if __name__ == "__main__":
hangmanner = Hangmanner()
hangmanner.play_hangman("test")
This uses the slicing function in python, where you can use the brackets and the [first:last] syntax to access an arbitrary range of any given collection. If either first or last is missing, the slice continues to the beginning or end of the collection, respectively. Above, current_guess[1:] returns current_guess from the second index to the last. current_guess[:i] returns current_guess from the first index up to the index preceding i, given that last is the exclusive end bound.
hiddenLet.replace('_',let) replaces all occurrences of _ with whatever let represents.
newWordList = [x if x==let else '_' for x in randWord]
newWord = ''.join(newWordList)

Categories

Resources