Okay so what I did was
def countvowels(st):
result=st.count("a")+st.count("A")+st.count("e")+st.count("E")+st.count("i")+st.count("I")+st.count("o")+st.count("O")+st.count("u")+st.count("U")
return result
This works(I'm aware indentation might be wrong in this post, but the way I have it indented in python, it works).
Is there a better way to do this? Using for loops?
I would do something like
def countvowels(st):
return len ([c for c in st if c.lower() in 'aeiou'])
There's definitely better ways. Here's one.
def countvowels(s):
s = s.lower()
return sum(s.count(v) for v in "aeiou")
You can do that using list comprehension
def countvowels(w):
vowels= "aAiIeEoOuU"
return len([i for i in list(w) if i in list(vowels)])
You could use regex pattern to do this easily. But it looks to me, that you want to do it without. So here is some code to do so:
string = "This is a test for vowel counting"
print [(i,string.count(i)) for i in list("AaEeIiOoUu")]
you can do it in various ways, first look in google before asking, i had copy pasted 2 of them
def countvowels(string):
num_vowels=0
for char in string:
if char in "aeiouAEIOU":
num_vowels = num_vowels+1
return num_vowels
data = raw_input("Please type a sentence: ")
vowels = "aeiou"
for v in vowels:
print v, data.lower().count(v)
You can also try Counter from collections (only available from Python 2.7+) as shown below . It'll show how many times each letter has been repeated.
from collections import Counter
st = raw_input("Enter the string")
print Counter(st)
But you want vowels specifically then try this.
import re
def count_vowels(string):
vowels = re.findall('[aeiou]', string, re.IGNORECASE)
return len(vowels)
st = input("Enter a string:")
print count_vowels(st)
Here is a version using map:
phrase=list("This is a test for vowel counting")
base="AaEeIiOoUu"
def c(b):
print b+":",phrase.count(b)
map(c,base)
Related
I'm trying to make a project in python so that whenever the program encounters a capital letter it makes a white space. So for example "helloThisIsMyProject" > hello This is My Project.
def project(w):
lst = []
for i in w:
lst.append(i)
for letter in lst:
if letter.isupper():
index = lst.index(letter)
lst.insert(index, " ")
continue
return "".join(lst)
print(project("helloThisIsMyProject"))
I'm having a problem with insert() and the for loop because the for loop is endlessly looping over the "T" from "This". I tried using continue to skip the letter T but it didn't fix my problem.
Those 1st three lines are simply
lst = list(w)
But you would find this more convenient:
lst = []
for letter in w:
if letter.isupper():
lst.append(" ")
lst.append(letter)
That is, rather than producing a list and going back to fix it up,
you could have it correct from the outset.
You can conditionally output a SPACE before you output the letter.
If you prefer to do it with a list comprehension,
you might enlist the aid of a helper:
def adjust(s: str) -> str:
"""Returns the input string, possibly whitespace adjusted."""
return " " + s if s.isupper() else s
lst = [adjust(letter)
for letter in w]
or more compactly:
lst = list(map(adjust, w))
You could use a join with a list comprehension that adds the space to individual characters:
def spaceCaps(w):
return "".join(" "*c.isupper()+c for c in w)
spaceCaps("helloThisIsMyProject")
'hello This Is My Project'
You could also use the sub() function from the regular expression module:
import re
def spaceCaps(w):
return re.sub("([A-Z])",r" \1",w)
I hope everyone is safe.
I am trying to go over a string and capitalize every first letter of the string.
I know I can use .title() but
a) I want to figure out how to use capitalize or something else in this case - basics, and
b) The strings in the tests, have some words with (') which makes .title() confused and capitalize the letter after the (').
def to_jaden_case(string):
appended_string = ''
word = len(string.split())
for word in string:
new_word = string[word].capitalize()
appended_string +=str(new_word)
return appended_string
The problem is the interpreter gives me "TypeError: string indices must be integers" even tho I have an integer input in 'word'. Any help?
thanks!
You are doing some strange things in the code.
First, you split the string just to count the number of words, but don't store it to manipulate the words after that.
Second, when iterating a string with a for in, what you get are the characters of the string, not the words.
I have made a small snippet to help you do what you desire:
def first_letter_of_word_upper(string, exclusions=["a", "the"]):
words = string.split()
for i, w in enumerate(words):
if w not in exclusions:
words[i] = w[0].upper() + w[1:]
return " ".join(words)
test = first_letter_of_word_upper("miguel angelo santos bicudo")
test2 = first_letter_of_word_upper("doing a bunch of things", ["a", "of"])
print(test)
print(test2)
Notes:
I assigned the value of the string splitting to a variable to use it in the loop
As a bonus, I included a list to allow you exclude words that you don't want to capitalize.
I use the original same array of split words to build the result... and then join based on that array. This a way to do it efficiently.
Also, I show some useful Python tricks... first is enumerate(iterable) that returns tuples (i, j) where i is the positional index, and j is the value at that position. Second, I use w[1:] to get a substring of the current word that starts at character index 1 and goes all the way to the end of the string. Ah, and also the usage of optional parameters in the list of arguments of the function... really useful things to learn! If you didn't know them already. =)
You have a logical error in your code:
You have used word = len(string.split()) which is of no use ,Also there is an issue in the for loop logic.
Try this below :
def to_jaden_case(string):
appended_string = ''
word_list = string.split()
for i in range(len(word_list)):
new_word = word_list[i].capitalize()
appended_string += str(new_word) + " "
return appended_string
from re import findall
def capitalize_words(string):
words = findall(r'\w+[\']*\w+', string)
for word in words:
string = string.replace(word, word.capitalize())
return string
This just grabs all the words in the string, then replaces the words in the original string, the characters inside the [ ] will be included in the word aswell
You are using string index to access another string word is a string you are accessing word using string[word] this causing the error.
def to_jaden_case(string):
appended_string = ''
for word in string.split():
new_word = word.capitalize()
appended_string += new_word
return appended_string
Simple solution using map()
def to_jaden_case(string):
return ' '.join(map(str.capitalize, string.split()))
In for word in string: word will iterate over the characters in string. What you want to do is something like this:
def to_jaden_case(string):
appended_string = ''
splitted_string = string.split()
for word in splitted_string:
new_word = word.capitalize()
appended_string += new_word
return appended_string
The output for to_jaden_case("abc def ghi") is now "AbcDefGhi", this is CammelCase. I suppose you actually want this: "Abc Def Ghi". To achieve that, you must do:
def to_jaden_case(string):
appended_string = ''
splitted_string = string.split()
for word in splitted_string:
new_word = word.capitalize()
appended_string += new_word + " "
return appended_string[:-1] # removes the last space.
Look, in your code word is a character of string, it is not index, therefore you can't use string[word], you can correct this problem by modifying your loop or using word instead of string[word]
So your rectified code will be:
def to_jaden_case(string):
appended_string = ''
for word in range(len(string)):
new_word = string[word].capitalize()
appended_string +=str(new_word)
return appended_string
Here I Changed The Third Line for word in string with for word in len(string), the counterpart give you index of each character and you can use them!
Also I removed the split line, because it's unnecessary and you can do it on for loop like len(string)
Word=input('please enter a word')
def cap(word):
for char in word:
if char in 'aeiou':
return letter.upper()
else:
return letter
result=cap(word)
print result
You return immediately after examining the first character. Instead, you should go over all of them, and modify the ones you need.
def cap(word):
result = ''
for letter in word:
if letter in 'aeiou':
result += letter.upper()
else:
result += letter
return result
Note, however, that this may be much easier to do with list comprehensions:
def cap(word):
return ''.join(l.upper() if l in 'aeiou' else l for l in word)
In python you can have functions that continuously return values — they're called generators. You just use yield instead of return. You can then use them as iterators, or call list on them to get the values:
word=input('please enter a word')
def cap(word):
for letter in word:
if letter in 'aeiou':
yield letter.upper()
else:
yield letter
result=cap(word)
print(''.join(list(result)))
However, if your goal is to translate a set of characters to another set of characters, there is a python string method for that: translate().
word=input('please enter a word')
upper_vowels = word.translate(str.maketrans('aeiou', 'AEIOU'))
print(upper_vowels)
This should be more efficient that looping and joining as well being easier to read. Also, you can save the translate table separately if you want to apply it to many strings.
I'm trying to write a function which given a string returns another string that flips its lowercase characters to uppercase and viceversa.
My current aproach is as follows:
def swap_case(s):
word = []
for char in s:
word.append(char)
for char in word:
if char.islower():
char.upper()
else:
char.lower()
str1 = ''.join(word)
However the string doesn't actually change, how should I alter the characters inside the loop to do so?
PS: I know s.swapcase() would easily solve this, but I want to alter the characters inside the string during a for loop.
def swap_case(s):
swapped = []
for char in s:
if char.islower():
swapped.append(char.upper())
elif char.isupper():
swapped.append(char.lower())
else:
swapped.append(char)
return ''.join(swapped)
you can use swapcase.
string.swapcase(s)
Return a copy of s, but with lower case letters converted to upper case and vice versa.
Source : Python docs
>>> name = 'Mr.Ed' or name= ["M","r",".","E","d"]
>>> ''.join(c.lower() if c.isupper() else c.upper() for c in name)
'mR.eD'
Your code is not working because you are not storing the chars after transforming them. You created a list with all chars and then, you access the values without actually saving them. Also, you should make your function return str1 or you will never get a result. Here's a workaround:
def swap_case(s):
word = []
for char in s:
if char.islower():
word.append(char.upper())
else:
word.append(char.lower())
str1 = ''.join(word)
return str1
By the way, I know you want to do it with a for loop, but you should know there are better ways to perform this which would be more pythonic.
You can use this code:
s = "yourString"
res = s.swapcase()
print(res)
Which will output:
YOURsTRING
def swap_case(s):
x = ''
for i in s:
if i.isupper():
i = i.lower()
else:
i = i.upper()
x += ''.join(i)
return x
As an example, lets say I wanted to list the frequency of each letter of the alphabet in a string. What would be the easiest way to do it?
This is an example of what I'm thinking of... the question is how to make allTheLetters equal to said letters without something like allTheLetters = "abcdefg...xyz". In many other languages I could just do letter++ and increment my way through the alphabet, but thus far I haven't come across a way to do that in python.
def alphCount(text):
lowerText = text.lower()
for letter in allTheLetters:
print letter + ":", lowertext.count(letter)
The question you've asked (how to iterate through the alphabet) is not the same question as the problem you're trying to solve (how to count the frequency of letters in a string).
You can use string.lowercase, as other posters have suggested:
import string
allTheLetters = string.lowercase
To do things the way you're "used to", treating letters as numbers, you can use the "ord" and "chr" functions. There's absolutely no reason to ever do exactly this, but maybe it comes closer to what you're actually trying to figure out:
def getAllTheLetters(begin='a', end='z'):
beginNum = ord(begin)
endNum = ord(end)
for number in xrange(beginNum, endNum+1):
yield chr(number)
You can tell it does the right thing because this code prints True:
import string
print ''.join(getAllTheLetters()) == string.lowercase
But, to solve the problem you're actually trying to solve, you want to use a dictionary and collect the letters as you go:
from collections import defaultdict
def letterOccurrances(string):
frequencies = defaultdict(lambda: 0)
for character in string:
frequencies[character.lower()] += 1
return frequencies
Use like so:
occs = letterOccurrances("Hello, world!")
print occs['l']
print occs['h']
This will print '3' and '1' respectively.
Note that this works for unicode as well:
# -*- coding: utf-8 -*-
occs = letterOccurrances(u"héĺĺó, ẃóŕĺd!")
print occs[u'l']
print occs[u'ĺ']
If you were to try the other approach on unicode (incrementing through every character) you'd be waiting a long time; there are millions of unicode characters.
To implement your original function (print the counts of each letter in alphabetical order) in terms of this:
def alphCount(text):
for character, count in sorted(letterOccurrances(text).iteritems()):
print "%s: %s" % (character, count)
alphCount("hello, world!")
the question is how to make
allTheLetters equal to said letters
without something like allTheLetters =
"abcdefg...xyz"
That's actually provided by the string module, it's not like you have to manually type it yourself ;)
import string
allTheLetters = string.ascii_lowercase
def alphCount(text):
lowerText = text.lower()
for letter in allTheLetters:
print letter + ":", lowertext.count(letter)
If you just want to do a frequency count of a string, try this:
s = 'hi there'
f = {}
for c in s:
f[c] = f.get(c, 0) + 1
print f
For counting objects, the obvious solution is the Counter
from collections import Counter
import string
c = Counter()
for letter in text.lower():
c[letter] += 1
for letter in string.lowercase:
print("%s: %d" % (letter, c[letter]))
Do you mean using:
import string
string.ascii_lowercase
then,
counters = dict()
for letter in string.ascii_lowercase:
counters[letter] = lowertext.count(letter)
All lowercase letters are accounted for, missing counters will have zero value.
using generators:
counters =
dict( (letter,lowertext.count(letter)) for letter in string.ascii_lowercase )
Something like this?
for letter in range(ord('a'), ord('z') + 1):
print chr(letter) + ":", lowertext.count(chr(letter))
Main question is "iterate through the alphabet":
import string
for c in string.lowercase:
print c
How get letter frequencies with some efficiency and without counting non-letter characters:
import string
sample = "Hello there, this is a test!"
letter_freq = dict((c,0) for c in string.lowercase)
for c in [c for c in sample.lower() if c.isalpha()]:
letter_freq[c] += 1
print letter_freq
How about this, to use letters, figures and punctuation (all usable to form a Django key):
import random
import string
chars = string.letters + string.digits + string.punctuation
chars_len = len(chars)
n = 40
print(''.join([chars[random.randint(0, chars_len)] for i in range(n)]))
Example result: coOL:V!D+P,&S*hzbO{a0_6]2!{4|OIbVuAbq0:
Just use:
import string
string.lowercase
string.uppercase
or
string.letters[:26]
string.letters[26:]
This is what I do:
import string
for x in list(string.lowercase):
print x