Only print the lowercase characters in a string - python

How can I write the code so python ONLY prints out the lower case letters of the string. In this case, it should exclude the P.
I tried this:
word = "Programming is fun!"
for letter in word:
if letter.lower():
print letter
But it doesn't solely print out the lowercase letters. How could I only get the lower-case characters out of the string instead of the whole string in lower-case.

You want letter.islower() (which tests), not letter.lower() (which converts).
If you want to print non-cased characters too, you'd check:
if letter.islower() or not letter.isalpha():

Try using islower instead :
letter.islower()

Yours doesn't work because you've called .lower(), which is a method of the String class - it changes the case of the letter in question, and results in True.
There are likely many ways to obtain the result you want, the simplest I can think of being:
word = "Hello World!"
for letter in word:
if letter.islower():
print(letter)
Note that there is an equality test in mine, which is what yours is missing.
EDIT: As other answers pointed out, .islower() is a more succinct way of checking the case of the letter. Similarly, .isupper() would print only the capital letters.

You could use
print filter(lambda c: c.islower(), word)

What will actually answer to your question (as i can tell from provided output) will be something like:
import string
word="Programming is fun!"
filter(lambda c: c.islower() or not(c.isupper() and c in string.printable), word)

Related

Python - Finding all uppercase letters in string

im a really beginner with python and I'm trying to modify codes that I have seen in lessons.I have tried the find all uppercase letters in string.But the problem is it only gives me one uppercase letter in string even there is more than one.
def finding_upppercase_itterative(string_input):
for i in range(len(string_input)):
if string_input[i].isupper:
return string_input[i]
return "No uppercases found"
How should i modify this code to give me all uppercase letters in given string. If someone can explain me with the logic behind I would be glad.
Thank You!
Edit 1: Thank to S3DEV i have misstyped the binary search algorithm.
If you are looking for only small changes that make your code work, one way is to use a generator function, using the yield keyword:
def finding_upppercase_itterative(string_input):
for i in range(len(string_input)):
if string_input[i].isupper():
yield string_input[i]
print(list(finding_upppercase_itterative('test THINGy')))
If you just print finding_upppercase_itterative('test THINGy'), it shows a generator object, so you need to convert it to a list in order to view the results.
For more about generators, see here: https://wiki.python.org/moin/Generators
This is the fixed code written out with a lot of detail to each step. There are some other answers with more complicated/'pythonic' ways to do the same thing.
def finding_upppercase_itterative(string_input):
uppercase = []
for i in range(len(string_input)):
if string_input[i].isupper():
uppercase.append(string_input[i])
if(len(uppercase) > 0):
return "".join(uppercase)
else:
return "No uppercases found"
# Try the function
test_string = input("Enter a string to get the uppercase letters from: ")
uppercase_letters = finding_upppercase_itterative(test_string)
print(uppercase_letters)
Here's the explanation:
create a function that takes string_input as a parameter
create an empty list called uppercase
loop through every character in string_input
[in the loop] if it is an uppercase letter, add it to the uppercase list
[out of the loop] if the length of the uppercase list is more than 0
[in the if] return the list characters all joined together with nothing as the separator ("")
[in the else] otherwise, return "No uppercases found"
[out of the function] get a test_string and store it in a variable
get the uppercase_letters from test_string
print the uppercase_letters to the user
There are shorter (and more complex) ways to do this, but this is just a way that is easier for beginners to understand.
Also: you may want to fix your spelling, because it makes code harder to read and understand, and also makes it more difficult to type the name of that misspelled identifier. For example, upppercase and itterative should be uppercase and iterative.
Something simple like this would work:
s = "My Word"
s = ''.join(ch for ch in s if ch.isupper())
return(s)
Inverse idea behind other StackOverflow question: Removing capital letters from a python string
The return statement in a function will stop the function from executing. When it finds an uppercase letter, it will see the return statement and stop.
One way to do this is to append letters to list and return them at the end:
def finding_uppercase_iterative(string_input):
letters = []
for i in range(len(string_input)):
if string_input[i].isupper():
letters.append(string_input[i])
if letters:
return letters
return "No uppercases found"

Anagram function says "ellhe" and "hello" are anagrams

I am trying to check whether two given strings are anagrams.
def Anagram(Word1, Word2):
if len(Word1.lower()) == len(Word2.lower()):
for Char in Word1.lower():
if Char in Word2.lower():
return (Word2,"Is An Anagram Of", Word1)
else:
return (Word2, "Is Not A Anagram", Word1)
else:
return (Word2, "Is Not A Anagram", Word1)
print(Anagram("Hello", "ellhe"))
The problem is that this prints that it is an anagram when it is not. FOr instance, it says that "ellhe" and "hello" are anagrams, but they differ by one letter ('o' vs a second 'e'). What am I doing wrong?
You're returning after only checking one letter, but your method is flawed anyway. Implemented correctly it will return true if the words contain the same letters, but will disregard how often they occur.
Here are a few things:
1) You're returning as soon as one character matches, not when the entire word matches
2) I believe you need to add some logic to handle situations where the same letter appears multiple times. Otherwise, helo and hello will show as anagrams of each other.
This is a one-liner: sort both strings and compare the sorted lists of characters:
if sorted(word1.lower()) ==
sorted(word2.lower()):
I trust you can do the rest of the routine, as you've already handled that logic.

Check that input is composed of letters from other word

I have this code:
print('abcdefg')
input('Arrange word from following letters: ')
I want to return True if the input consists of letters from the printed string but it doesn't have to have all of printed letters.
That's a perfect use case for sets especially for set.issubset:
print('abcdefg')
given_input = input('Arrange word from following letters: ')
if set(given_input).issubset('abcdefg'):
print('True')
else:
print('False')
or directly print (or return) the result of the issubset operation without if and else:
print(set(given_input).issubset('abcdefg'))
This sounds a little like homework...
Basically you would need to do this: Store both strings in variables. e.g. valid_chars and s.
Then loop through s one character at a time. For each character check if it is in valid_chars (using the in operator). If any character is not found in valid_chars then you should return False. If you get to the end of the loop, return True.
If the valid_chars string is very long it would be better to first put them into a set but for short strings this is not necessary.

How to load an uppercase alphabet?

I have been trying to create a Caesar cipher program. To make it as inclusive as possible I want to be able to use upper case letters as well. I know how to load a lower case alphabet:
alphabet = string.ascii_lowercase * 2
(I have timed it by two to allow the user to encrypt all letters)
I would really like some help. It is my first time submitting a question and I would appreciate any help I get
If there is a string.ascii_lowercase then surely there is a string.ascii_uppercase. Give it a try.
There is string.ascii_uppercase as well as string.ascii_lowercase (documentation). For testing if a letter is upper case and do something for uppercase letters in a message you can do this:
for letter in message:
if letter in string.ascii_uppercase:
# do something
You can also use isupper() method (documentation):
for letter in message:
if letter.isupper():
# do something
If you want to check whether the whole message is upper case, then isupper() is actually better as it checks the whole string:
if message.isupper():
# do something
You can use
string.uppercase
This is locale-dependent, and value will be updated when locale.setlocale() is called.
Please refer - https://docs.python.org/2/library/string.html
This loop will make a string with all uppercase letters and save it in letters_str
letters_str = ''
for x in range(65,91):
letters_str+=chr(x)

Find multiple list items within a string

Working on a problem in which I am trying to get a count of the number of vowels in a string. I wrote the following code:
def vowel_count(s):
count = 0
for i in s:
if i == 'a' or i == 'e' or i == 'i' or i == 'o' or i == 'u':
count += 1
print count
vowel_count(s)
While the above works, I would like to know how to do this more simply by creating a list of all vowels, then looping my If statement through that, instead of multiple boolean checks. I'm sure there's an even more elegant way to do this with import modules, but interested in this type of solution.
Relative noob...appreciate the help.
No need to create a list, you can use a string like 'aeiou' to do this:
>>> vowels = 'aeiou'
>>> s = 'fooBArSpaM'
>>> sum(c.lower() in vowels for c in s)
4
You can actually treat a string similarly to how you would a list in python (as they are both iterables), for example
vowels = 'aeiou'
sum(1 for i in s if i.lower() in vowels)
For completeness sake, others suggest vowels = set('aeiou') to allow not matching checks such as 'eio' in vowels. However note if you are iterating over your string in a for loop one character at a time, you won't run into this problem.
A weird way around this is the following:
vowels = len(s) - len(s.translate(None, 'aeiou'))
What you are doing with s.translate(None, 'aeiou') is creating a copy of the string removing all vowels. And then checking how the length differed.
Special note: the way I'm using it is even part of the official documentation
What is a vowel?
Note, though, that method presented here only replaces exactly the characters present in the second parameter of the translate string method. In particular, this means that it will not replace uppercase versions characters, let alone accented ones (like áèïôǔ).
Uppercase vowels
Solving the uppercase ones is kind of easy, just do the replacemente on a copy of the string that has been converted to lowercase:
vowels = len(s) - len(s.lower().translate(None, 'aeiou'))
Accented vowels
This one is a little bit more convoluted, but thanks to this other SO question we know the best way to do it. The resulting code would be:
from unicodedate import normalize
# translate special characters to unaccented versions
normalized_str = normalize('NFD', s).encode('ascii', 'ignore')
vowels = len(s) - len(normalized_str.lower().translate(None, 'aeiou'))
You can filter using a list comprehension, like so:
len([letter for letter in s if letter in 'aeiou'])

Categories