Python Programming String Handling Functions - python

So, I'm a beginner to programming. I am trying to create a program where the user can input a sentence and the program will tell the user how many letters are in that sentence.
counter=0
wrd=raw_input("Please enter a short sentence.")
if wrd.isalpha():
counter=counter+1
print "You have" + str(counter) +"in your sentence."
When I enter this, my output is blank. What is my mistake in this program?

You need to indent code inside if blocks. In the code you have provided, you've forgotten to indent counter = counter + 1.
You are missing a loop across all characters of wrd. Try this instead,
counter = 0
wrd = raw_input("Please enter a short sentence.")
# Iterate over every character in string
for letter in wrd:
# Check if the letter is an alphabet
if letter.isalpha():
# Increment counter only in this condition
counter += 1
print "You have " + str(counter) + " in your sentence."

First of all as #kalpesh mentioned, the statement counter=counter+1 should be indented.
Second of all, you need to iterate over the entire string entered and then count the number of characters or whatever the logic you need.
counter=0
wrd=raw_input("Please enter a short sentence.")
for i in wrd:
if i.isalpha():
counter = counter+1
print "You have " + str(counter) +"in your sentence."
Once you start learning more, then you can use the below code,
counter=[]
count = 0
wrd=raw_input("Please enter a short sentence.")
counter = [len(i) for i in wrd.split() if i.isalpha()]
print "You have " + str(sum(counter)) +"in your sentence."
I am just splitting the word and then checking if it is alpha or not and using the list comprehension to iterate over the string entered.

wrd.isalpha() returns a boolean (true or false). So if the function returns true, counter=counter+1 will be called once (and only once). You need to iterate through every letter of wrd and call isalpha() on each letter.

You could always remove the spaces from your sentence using replace() then use len() to get how many characters are in the sentence.
For example:
sentence = input("Type in a sentence: ") # Ask the user to input a sentence
sentence = sentence.replace(" ", "") # Replace the spaces in the sentence with nothing
print("Your sentence is " + str(len(sentence)) + " characters long") # Use len() to print out number of letters in the sentence

Related

How do I remove space at the end of an output in python?

I have a program that counts and prints all words in a sentence that contains a specific character(ignoring case).
Code in Python -
item=input()
ip=input().tolower()
r=ip.count(item)
print(r)
ip=ip.split()
for word in ip:
if item in word:
print((word), end=' ')
This program works as expected but for the last word that is printed I don't want a white-space after it.
If anyone could guide me on how to remove the space it would be appreciated.
Why don't you use list comprehension and str.join?
print(' '.join([w for w in ip if item in w]))
I don't think there's a way to remove that, as it's a part of your terminal. Best answer I can give you.
I expanded on the code though, cause I was kinda bored.
sentence = input("Enter a sentence: ").lower()
pull = input("Which character(s) do you want to count?: ").lower()
for c in pull:
occurrences = 0
for character in sentence:
if c == character:
occurrences+=1
if c!=" ": print("\'%s\' appears %d times"%(c, occurrences))
for word in sentence.split():
occurrences = 0
for character in word:
if c == character:
occurrences+=1
if occurrences == 1:
print(("1 time in \'%s\'")%(word))
elif occurrences > 0:
print(("%d times in \'%s\'")%(occurrences,word))
+The solution with a list comprehension appears more concise, but if you prefer an alternative you can use the following. It was tested and worked with the example in the picture.
# Amended solution. The commented lines are the amendment.
item = input('Letter: ')
ip = input('Input: ').lower()
r = ip.count(item)
print(r)
ip = ip.split()
outputString = '' # Added: Initialise an empty string to keep the answer
for word in ip:
if item in word:
outputString += word + ' ' # Changed: Accumulates the answer in a string
print(outputString[:-1]) # Added: Prints all the string's characters
# except the last one, which is the additional space
You're close, just change your print statement from print((word), end=' ') to print((word), end=''). Your print statement has a whitespace for the end but you don't want the whitespace so make the end an empty string.

How can I do this specific replacement

string = input("Enter a string:")
character = input ("Enter a character:")
if character in string: #checks string to see if character is in it
print ("Character found!")
else:
print ("Character not found!")
blank = (" _ " * len(string))
print (blank)
I am making a hangman game and I am stuck at this part.
How can I make it so that when the person guesses a letter it replaces the specific " _ " for where the letter should be? Should I be using a for loop to go through all the " _ " 's and then use an if statement?
If someone could show me how it would be great.
You can use a method similar to the following to update your guess string each time the player guesses something.
def update_guesses(current_guess_string, key_string, character_guessed):
out_string = ""
for i in range(len(current_guess_string)):
if current_guess_string[i] == "_" and key_string[i] == character_guessed):
out_string += character_guessed
else: out_string += current_guess_string[i]
return out_string
Building on your code, here's a set of changes that get you to a working game:
Set your string input to a fixed case and move your blank initialization to just after string input. Change them both to lists so you can modify
them as needed:
# normalize case and convert to a mutable data structure
string = list(input("Enter a string: ").lower())
# the blank list matches the string except it starts all blanks
blank = list("_" * len(string))
Get a loop going for handling guesses. Here I'm stopping the loop when the string list is all one character, presumably blanks, as we'll be swapping characters between the blank and input string lists:
while len(set(string)) > 1: # when the string is all blanks, stop
Make sure to cleanup the user input to be only one character and change it to the same case as the string input:
# normalize case on input and make sure to only get 1 character
character = input("Enter a character: ").lower()[0]
After you test if the character is in the string, swap the character, by position, with a character in the blank string. Do this in a loop so you get all instances of the guessed character:
if character in string: # checks string to see if character is in it
print("Character found!")
# find the character in the string and swap it with what's in
# the blank string so we can handle multiple same characters
# correctly
while character in string:
index = string.index(character)
string[index] = blank[index]
blank[index] = character
else:
print("Character not found!")
The last step in the main loop is to print the current state of the guesses:
# print correct guesses and blanks
print(*blank, sep='')

Creation of a Function that transforms sentence in Python

So I am trying to create a function that calls two functions within the function where one function called "encode" checks if the first letter of a word is a vowel and if yes it will add "way" to the end of the word and if the word starts with a consonant it will move the first letter to the third position in the word and adds gar.
my problem is creating that function that calls from the encode function to read a sentence and change each word accordingly based on the first letter.
So here are some text cases for the function:
encode() function:
The output will look like this:
Please enter your message: python is fun
The secret message is: ythonpar isway unfar
translation is correct when words are separated by more than one space character.
Please enter your message: simple is better than complex
The secret message is: implesar isway etterbar hantar omplexcar
Here is my script. They are suppose to be connected.
def get_input():
user_input = input('Please enter a message: ')
more_message = True
while more_message:
user_input = input('Please enter a message: ')
if not user_input==' ':
more_grades = False
return
def starts_with_vowel(word):
while True:
data = word
the_vowel = "aeiou"
if word[0].lower() in the_vowel:
print ('true')
else:
print ('false')
return
def encode(word):
while True:
data = starts_with_vowel(word)
the_vowel = "aeiou"
if word[0].lower() in the_vowel:
new_word=word+'way'
print ('The secret word is:',new_word)
else:
new_word2=word+'ar'
scrambled_word=new_word2[1:-2]+new_word2[0]+new_word2[3]+new_word2[4]
print (scrambled_word)
print ('The secret word is:',new_word2)
return
def translate(text):
secret_message= encode(text)
return (secret_message)
translate('gin is a boy')
A better approach would be to use split on the sentence (input) and loop over the words:
vowels = 'aeiou'
sentence = 'python is fun'
new_words = []
for word in sentence.split():
if word[0].lower() in vowels:
new_words.append(word+'way')
else:
new_words.append(word[1:3]+word[0]+word[3:]+'gar')
' '.join(new_words)
'ytphongar isway unfgar'
I think in the first part of the code you will need to change the more_grades section with more_message, because first off more_grades has not been initialized and more_messages is controlling your loop so i think that's what you meant to do. Don't worry I believe that's only one error I have caught I will check the rest of the code and get back to you. Don't stress it.Happy coding :-)

How to repeat the first characters of every word in a sentence timed by three in python?

I want to make a function that takes a string (sentence) as an argument then takes the first word and saves every character that is a konsonant up to the first vowel (including the vowel) and save it in an empty string. Then i want it to take the second one and do the same thing... and so on... and so on...
Ex. input -> "This is good" output -> ThiThiThi iii gogogo
This is what i have came up with so far:
def lang(text):
alist=text.split()
kons="nrmg" nytext=" "
for word in alist:
for tkn in word:
if tkn in kons:
nytext+=tkn
else:
nytext+=tkn
nytext=nytext*3
nytext=nytext+"" break
return nytext
print(lang("This is good"))
what i get is this -> T T Ti T T Ti T T Ti
What am i doing wrong?
Any help is appreciated!
Thanks :)
So the first thing is if you want to keep track of each word differently, then you need to use another variable(I called retText) because each word should be processed separately and results should be collected in the different variable.
Secondly, if you are looking for finding letters up to first vowel, then you need to check if the letter is vowel or not. kons variable holds the vowels and inside of the code, there is an
if not tkn in kons:
statement which checks if the tkn is vowel or not. Here is the full code:
def lang(text):
alist=text.split()
kons="aeiouAEIOU"
retText=""
for word in alist:
nytext=""
for tkn in word:
if not tkn in kons:
nytext+=tkn
else:
nytext+=tkn
retText += nytext*3 + " "
break
else:
retText += word*3 + " "
return retText
print(lang("This is good"))

How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace?

How would I go about counting the words in a sentence? I'm using Python.
For example, I might have the string:
string = "I am having a very nice 23!#$ day. "
That would be 7 words. I'm having trouble with the random amount of spaces after/before each word as well as when numbers or symbols are involved.
str.split() without any arguments splits on runs of whitespace characters:
>>> s = 'I am having a very nice day.'
>>>
>>> len(s.split())
7
From the linked documentation:
If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.
You can use regex.findall():
import re
line = " I am having a very nice day."
count = len(re.findall(r'\w+', line))
print (count)
s = "I am having a very nice 23!#$ day. "
sum([i.strip(string.punctuation).isalpha() for i in s.split()])
The statement above will go through each chunk of text and remove punctuations before verifying if the chunk is really string of alphabets.
This is a simple word counter using regex. The script includes a loop which you can terminate it when you're done.
#word counter using regex
import re
while True:
string =raw_input("Enter the string: ")
count = len(re.findall("[a-zA-Z_]+", string))
if line == "Done": #command to terminate the loop
break
print (count)
print ("Terminated")
Ok here is my version of doing this. I noticed that you want your output to be 7, which means you dont want to count special characters and numbers. So here is regex pattern:
re.findall("[a-zA-Z_]+", string)
Where [a-zA-Z_] means it will match any character beetwen a-z (lowercase) and A-Z (upper case).
About spaces. If you want to remove all extra spaces, just do:
string = string.rstrip().lstrip() # Remove all extra spaces at the start and at the end of the string
while " " in string: # While there are 2 spaces beetwen words in our string...
string = string.replace(" ", " ") # ... replace them by one space!
def wordCount(mystring):
tempcount = 0
count = 1
try:
for character in mystring:
if character == " ":
tempcount +=1
if tempcount ==1:
count +=1
else:
tempcount +=1
else:
tempcount=0
return count
except Exception:
error = "Not a string"
return error
mystring = "I am having a very nice 23!#$ day."
print(wordCount(mystring))
output is 8
How about using a simple loop to count the occurrences of number of spaces!?
txt = "Just an example here move along"
count = 1
for i in txt:
if i == " ":
count += 1
print(count)
import string
sentence = "I am having a very nice 23!#$ day. "
# Remove all punctuations
sentence = sentence.translate(str.maketrans('', '', string.punctuation))
# Remove all numbers"
sentence = ''.join([word for word in sentence if not word.isdigit()])
count = 0;
for index in range(len(sentence)-1) :
if sentence[index+1].isspace() and not sentence[index].isspace():
count += 1
print(count)

Categories

Resources