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)
Related
I just want to make an input text:
text = input('Your text: ')
And after the user types the text, I want the programme to take only capital letters from it and print them.
What does the easiest way mean? - Well, try to not use
functions, lists and stuff like that. Try to make the programme as
easy as possible. Thanks beforehand.
for char in text:
if char.isupper():
print(char)
A couple of inline ways to do it:
List comprehensions:
uppercase_chars = [char for char in text if char.isupper()]
Filter functions:
uppercase_chars = filter(str.isupper,text)
Although these answers both return lists, we can easily collapse them to strings using str.join like so:
''.join(uppercase_chars)
These are not as simple as BVB44's answer, but they're much more likely to be seen in real-world code.
Use a for loop to check if each character is uppercase, and add it to a new variable if it is. How this works is:
For every character in the variable my_string, Python checks if the character is uppercase. If it is, it adds it to the variable output. This keeps everything on one line.
my_string = input("Type some stuff ")
output = ''
for char in my_string:
if char.isupper():
output = output + char
print(output)
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"
This may seem like a beginner question, but I'm new to python and don't know much.
So this program is supposed to take the inputted string and replace all the characters in it with the alphabet in order, for eg. inputting "python" should output "abcdef" and inputting "program" should output "abcdefg" etc.
import string
char = input()
new_char = "-"
for i, let in enumerate(char):
new_char = char.replace(let, string.ascii_letters[i])
char = new_char
print(new_char)
For some reason, it only replaces some of the characters with random letters and not in order. But when I replace the i in string.ascii_letters[i] with any index from 0 - 51, then the program works as intended. Could someone explain to me why this program is not working as intended?
You don't need to complicate it. ascii_lowercase prints all the lower case letters. It returns a string. So taking advantage of slicing, you can do string slicing
import string
char = input()
new_char = string.ascii_lowercase[:len(char)]
print(new_char)
.replace replaces all the occurrences of a particular substring. So, if you do program and you replace it, it becomes arogram. Notice that you assign that to new_char. With next iteration, it will become abogbam
Use chr() to convert from int to characters (don't forget that the input is ASCII char codes)
If you don't care about the value in the input string, just iterate over for i in range(len(input_string)):
char.replace(old_chr, new_chr) will replace all instances of old_chr throughout the whole string (what if your input is hello?)
How about:
import string
char = input()
new_char = ''
for x in range(len(char)):
new_char += string.ascii_letters[x]
print(new_char)
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)
I am trying to import the alphabet but split it so that each character is in one array but not one string. splitting it works but when I try to use it to find how many characters are in an inputted word I get the error 'TypeError: Can't convert 'list' object to str implicitly'. Does anyone know how I would go around solving this? Any help appreciated. The code is below.
import string
alphabet = string.ascii_letters
print (alphabet)
splitalphabet = list(alphabet)
print (splitalphabet)
x = 1
j = year3wordlist[x].find(splitalphabet)
k = year3studentwordlist[x].find(splitalphabet)
print (j)
EDIT: Sorry, my explanation is kinda bad, I was in a rush. What I am wanting to do is count each individual letter of a word because I am coding a spelling bee program. For example, if the correct word is 'because', and the user who is taking part in the spelling bee has entered 'becuase', I want the program to count the characters and location of the characters of the correct word AND the user's inputted word and compare them to give the student a mark - possibly by using some kind of point system. The problem I have is that I can't simply say if it is right or wrong, I have to award 1 mark if the word is close to being right, which is what I am trying to do. What I have tried to do in the code above is split the alphabet and then use this to try and find which characters have been used in the inputted word (the one in year3studentwordlist) versus the correct word (year3wordlist).
There is a much simpler solution if you use the in keyword. You don't even need to split the alphabet in order to check if a given character is in it:
year3wordlist = ['asdf123', 'dsfgsdfg435']
total_sum = 0
for word in year3wordlist:
word_sum = 0
for char in word:
if char in string.ascii_letters:
word_sum += 1
total_sum += word_sum
# Length of characters in the ascii letters alphabet:
# total_sum == 12
# Length of all characters in all words:
# sum([len(w) for w in year3wordlist]) == 18
EDIT:
Since the OP comments he is trying to create a spelling bee contest, let me try to answer more specifically. The distance between a correctly spelled word and a similar string can be measured in many different ways. One of the most common ways is called 'edit distance' or 'Levenshtein distance'. This represents the number of insertions, deletions or substitutions that would be needed to rewrite the input string into the 'correct' one.
You can find that distance implemented in the Python-Levenshtein package. You can install it via pip:
$ sudo pip install python-Levenshtein
And then use it like this:
from __future__ import division
import Levenshtein
correct = 'because'
student = 'becuase'
distance = Levenshtein.distance(correct, student) # distance == 2
mark = ( 1 - distance / len(correct)) * 10 # mark == 7.14
The last line is just a suggestion on how you could derive a grade from the distance between the student's input and the correct answer.
I think what you need is join:
>>> "".join(splitalphabet)
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
join is a class method of str, you can do
''.join(splitalphabet)
or
str.join('', splitalphabet)
To convert the list splitalphabet to a string, so you can use it with the find() function you can use separator.join(iterable):
"".join(splitalphabet)
Using it in your code:
j = year3wordlist[x].find("".join(splitalphabet))
I don't know why half the answers are telling you how to put the split alphabet back together...
To count the number of characters in a word that appear in the splitalphabet, do it the functional way:
count = len([c for c in word if c in splitalphabet])
import string
# making letters a set makes "ch in letters" very fast
letters = set(string.ascii_letters)
def letters_in_word(word):
return sum(ch in letters for ch in word)
Edit: it sounds like you should look at Levenshtein edit distance:
from Levenshtein import distance
distance("because", "becuase") # => 2
While join creates the string from the split, you would not have to do that as you can issue the find on the original string (alphabet). However, I do not think is what you are trying to do. Note that the find that you are trying attempts to find the splitalphabet (actually alphabet) within year3wordlist[x] which will always fail (-1 result)
If what you are trying to do is to get the indices of all the letters of the word list within the alphabet, then you would need to handle it as
for each letter in the word of the word list, determine the index within alphabet.
j = []
for c in word:
j.append(alphabet.find(c))
print j
On the other hand if you are attempting to find the index of each character within the alphabet within the word, then you need to loop over splitalphabet to get an individual character to find within the word. That is
l = []
for c within splitalphabet:
j = word.find(c)
if j != -1:
l.append((c, j))
print l
This gives the list of tuples showing those characters found and the index.
I just saw that you talk about counting the number of letters. I am not sure what you mean by this as len(word) gives the number of characters in each word while len(set(word)) gives the number of unique characters. On the other hand, are you saying that your word might have non-ascii characters in it and you want to count the number of ascii characters in that word? I think that you need to be more specific in what you want to determine.
If what you are doing is attempting to determine if the characters are all alphabetic, then all you need to do is use the isalpha() method on the word. You can either say word.isalpha() and get True or False or check each character of word to be isalpha()