Python: How to print a word one letter at a time - python

How do I use Python to print a word one letter at a time? Any help would be appreciated.

If i understood you correctly than you can use the following code:
for word in text.split():
print word
else if you need to print word's letters:
for let in word:
print let
In case you need to skip punctuation and so on you can also use regEx:
tst = 'word1, word2 word3;'
from re import findall
print findall(r'\w+', tst)
Or not very pythonic:
skipC = [':','.', ',', ';']# add any if needed
text= 'word1, word2. word3;'
for x in skipC:
text = text.replace(x, ' ')
for word in text.split():
print word

Related

Trouble with simple acronym program python

I'm trying to make an acronym program where the user can enter 1 word per line and after entering a blank space the program will output the word created by the first letter of each word. It is printing a whitespace after the output which I don't want. Any Ideas on how to remove that? More information below:
E.g
User input:
Word: Hello
Word: World
Desired output:
Hello World <-- whitespace here that I don't want
-- HW
My Current Code that works:
words = []
word = input('Word: ')
while word:
words.append(word)
word = input('Word: ') #Word input
for word in words:
print(word, end=" ") #displays all words on one line
# Printing a white space ^
# Wanting to print this code on a new line
first_letters = ''.join([word[0] for word in words])
new=first_letters.upper()
print("\n-- " + new)
You're almost there. Combining what you had with num and print:
for word in words:
print(word[:1], end="") # Display all first letters without spaces.
This code does everything you want
words = []
word = input('Word: ')
while word:
words.append(word)
word = input('Word: ') #Word input
print(' '.join(words))
first_letters = ''.join([word[0] for word in words])
new=first_letters.upper()
print("-- " + new)
Simply this?
words = ['Hello','World']
print(' '.join(w for w in words))
print('-- '+''.join(w[0] for w in words))
Given array of strings words. There are several approaches to get first letters of the words. Few of them are below.
First approach
first_letters = ''
for word in words:
first_letters += word[0]
print(first_letters)
Second approach
first_letters = ''.join([word[0] for word in words])
print(first_letters)

Python: Iterate through string and print only specific words

I'm taking a class in python and now I'm struggling to complete one of the tasks.
The aim is to ask for an input, integrate through that string and print only words that start with letters > g. If the word starts with a letter larger than g, we print that word. Otherwise, we empty the word and iterate through the next word(s) in the string to do the same check.
This is the code I have, and the output. Would be grateful for some tips on how to solve the problem.
# [] create words after "G" following the Assignment requirements use of functions, menhods and kwyowrds
# sample quote "Wheresoever you go, go with all your heart" ~ Confucius (551 BC - 479 BC)
# [] copy and paste in edX assignment page
quote = input("Enter a sentence: ")
word = ""
# iterate through each character in quote
for char in quote:
# test if character is alpha
if char.isalpha():
word += char
else:
if word[0].lower() >= "h":
print(word.upper())
else:
word=""
Enter a sentence: Wheresoever you go, go with all your heart
WHERESOEVER
WHERESOEVERYOU
WHERESOEVERYOUGO
WHERESOEVERYOUGO
WHERESOEVERYOUGOGO
WHERESOEVERYOUGOGOWITH
WHERESOEVERYOUGOGOWITHALL
WHERESOEVERYOUGOGOWITHALLYOUR
The output should look like,
Sample output:
WHERESOEVER
YOU
WITH
YOUR
HEART
Simply a list comprehension with split will do:
s = "Wheresoever you go, go with all your heart"
print(' '.join([word for word in s.split() if word[0].lower() > 'g']))
# Wheresoever you with your heart
Modifying to match with the desired output (Making all uppercase and on new lines):
s = "Wheresoever you go, go with all your heart"
print('\n'.join([word.upper() for word in s.split() if word[0].lower() > 'g']))
'''
WHERESOEVER
YOU
WITH
YOUR
HEART
'''
Without list comprehension:
s = "Wheresoever you go, go with all your heart"
for word in s.split(): # Split the sentence into words and iterate through each.
if word[0].lower() > 'g': # Check if the first character (lowercased) > g.
print(word.upper()) # If so, print the word all capitalised.
Here is a readable and commented solution. The idea is first to split the sentence into a list of words using re.findall (regex package) and iterate through this list, instead of iterating on each character as you did. It is then quite easy to print only the words starting by a letter greater then 'g':
import re
# Prompt for an input sentence
quote = input("Enter a sentence: ")
# Split the sentence into a list of words
words = re.findall(r'\w+', quote)
# Iterate through each word
for word in words:
# Print the word if its 1st letter is greater than 'g'
if word[0].lower() > 'g':
print(word.upper())
To go further, here is also the one-line style solution based on exactly the same logic, using list comprehension:
import re
# Prompt for an input sentence
quote = input("Enter a sentence: ")
# Print each word starting by a letter greater than 'g', in upper case
print(*[word.upper() for word in re.findall(r'\w+', quote) if word[0].lower() > 'g'], sep='\n')
s = "Wheresoever you go, go with all your heart"
out = s.translate(str.maketrans(string.punctuation, " "*len(string.punctuation)))
desired_result = [word.upper() for word in out.split() if word and word[0].lower() > 'g']
print(*desired_result, sep="\n")
Your problem is that you're only resetting word to an empty string in the else clause. You need to reset it to an empty string immediately after the print(word.upper()) statement as well for the code as you've wrote it to work correctly.
That being said, if it's not explicitly disallowed for the class you're taking, you should look into string methods, specifically string.split()

How to make this code disregard all punctuation from the sentence?

I've created this code to analyse an input sentence to allow for the user to search for a certain word within it. However, I can't seem to figure out how to make it so all the punctuation in the input sentence is disregarded. I need this because, if a sentence such as "hello there, friend" is input, the word "there" is counted as "there," and so if the user is searching for "there" it says it is not in the sentence. Please help me. I'm really new to python.
print("Please enter a sentence")
sentence=input()
lowersen=(sentence.lower())
print(lowersen)
splitlowersen=(lowersen.split())
print (splitlowersen)
print("Enter word")
word=input()
lword=(word.lower())
if lword in splitlowersen:
print(lword, "is in sentence")
for i, j in enumerate (splitlowersen):
if j==lword:
print(""+lword+"","is in position", i+1)
if lword not in splitlowersen:
print (lword, "is not in sentence")
print("Please enter a sentence")
sentence=input()
lowersen=(sentence.lower())
print(lowersen)
splitlowersen=(lowersen.strip())
#to remove punctuations
splitlowersen = "".join(c for c in splitlowersen if c not in ('!','.',':'))
print("Enter word")
word=input()
lword=(word.lower())
if lword in splitlowersen:
print(lword, "is in sentence")
for i, j in enumerate (splitlowersen):
if j==lword:
print(""+lword+"","is in position", i+1)
if lword not in splitlowersen:
print (lword, "is not in sentence")
Output:
Please enter a sentence
hello, friend
hello, friend
Enter word
hello
hello is in sentence
You could split the string on all punctuation marks:
s = "This, is a line."
f = s.split(".,!?")
>>>> f = ["This", "is", "a", "line"]
This is a little long winded maybe but in python3.
# This will remove all non letter characters and spaces from the sentence
sentence = ''.join(filter(lambda x: x.isalpha() or x == ' ', sentence)
# the rest of your code will work after this.
There are a couple of advanced concepts in here.
Filter will take a function and an iterible returning a generator with the items that don't return true from the function
https://docs.python.org/3/library/functions.html#filter
Lambda will create an anonymous function that will check each letter for us.
https://docs.python.org/3/reference/expressions.html#lambda
x.isalpha() will check that the letter in question is actually a letter.
followed by x == ' ' to see it it could be a space.
https://docs.python.org/3.6/library/stdtypes.html?highlight=isalpha#str.isalpha
''.join will take the results of the filter and put it back into a string for you.
https://docs.python.org/3.6/library/stdtypes.html?highlight=isalpha#str.join
Or you could use nltk package for tokenizing your text which does the sentence tokenization as you would be expecting and it also avoids the common pitfalls of punctuation as 'Mr.' --> This will not be broken down based on the punctuation.
from nltk.tokenize import word_tokenize
string = "Hello there, friend"
words = word_tokenize(string)
print(words)
OUTPUT
['Hello', 'there', ',', 'friend']
So I guess you should try using nltk package and see if it works.
Click this link here for better understanding.
Hope this helps :)

How do I print out individual words within my list?

I am trying to print each word from my list onto separate lines, however it is printing each letter onto individual lines
Words = sentence.strip()
for word in sentence:
print (word)
My full code (for anyone wondering) is:
import csv
file = open("Task2.csv", "w")
sentence = input("Please enter a sentence: ")
Words = sentence.strip()
for word in sentence:
print (word)
for s in Words:
Positions = Words.index(s)+1
file.write(str(Words) + (str(Positions) + "\n"))
file.close()
You forgot to split sentence and use "Words" not "sentence" in first for loop.
#file = open("Task2.csv", "w")
sentence = input("Please enter a sentence: ")
Words = sentence.split()
for word in Words:
print (word)
for s in Words:
Positions = Words.index(s)+1
#file.write(str(Words) + (str(Positions) + "\n"))
#file.close()
Output:
C:\Users\dinesh_pundkar\Desktop>python c.py
Please enter a sentence: I am Dinesh
I
am
Dinesh
C:\Users\dinesh_pundkar\Desktop>
You need to used str.split() instead of str.strip().
str.strip() only removes the leading and trailing whitespaces in a string:
>>> my_string = ' This is a sentence. '
>>> my_string.strip()
'This is a sentence.'
str.split() does what you want which is return a list of the words in the string; by default, using whitespace as the delimiter string:
>>> my_string = ' This is a sentence. '
>>> my_string.split()
['This', 'is', 'a', 'sentence.']
So, your code should look more like:
words = sentence.split()
for word in sentence:
print(word)

How do I print words with only 1 vowel?

my code so far, but since i'm so lost it doesn't do anything close to what I want it to do:
vowels = 'a','e','i','o','u','y'
#Consider 'y' as a vowel
input = input("Enter a sentence: ")
words = input.split()
if vowels == words[0]:
print(words)
so for an input like this:
"this is a really weird test"
I want it to only print:
this, is, a, test
because they only contains 1 vowel.
Try this:
vowels = set(('a','e','i','o','u','y'))
def count_vowels(word):
return sum(letter in vowels for letter in word)
my_string = "this is a really weird test"
def get_words(my_string):
for word in my_string.split():
if count_vowels(word) == 1:
print word
Result:
>>> get_words(my_string)
this
is
a
test
Here's another option:
import re
words = 'This sentence contains a bunch of cool words'
for word in words.split():
if len(re.findall('[aeiouy]', word)) == 1:
print word
Output:
This
a
bunch
of
words
You can translate all the vowels to a single vowel and count that vowel:
import string
trans = string.maketrans('aeiouy','aaaaaa')
strs = 'this is a really weird test'
print [word for word in strs.split() if word.translate(trans).count('a') == 1]
>>> s = "this is a really weird test"
>>> [w for w in s.split() if len(w) - len(w.translate(None, "aeiouy")) == 1]
['this', 'is', 'a', 'test']
Not sure if words with no vowels are required. If so, just replace == 1 with < 2
You may use one for-loop to save the sub-strings into the string array if you have checked he next character is a space.
Them for each substring, check if there is only one a,e,i,o,u (vowels) , if yes, add into the another array
aFTER THAT, FROM another array, concat all the strings with spaces and comma
Try this:
vowels = ('a','e','i','o','u','y')
words = [i for i in input('Enter a sentence ').split() if i != '']
interesting = [word for word in words if sum(1 for char in word if char in vowel) == 1]
i found so much nice code here ,and i want to show my ugly one:
v = 'aoeuiy'
o = 'oooooo'
sentence = 'i found so much nice code here'
words = sentence.split()
trans = str.maketrans(v,o)
for word in words:
if not word.translate(trans).count('o') >1:
print(word)
I find your lack of regex disturbing.
Here's a plain regex only solution (ideone):
import re
str = "this is a really weird test"
words = re.findall(r"\b[^aeiouy\W]*[aeiouy][^aeiouy\W]*\b", str)
print(words)

Categories

Resources