Is There an Already Made Alphabet List In Python? [duplicate] - python

This question already has answers here:
Alphabet range in Python
(8 answers)
Closed 7 months ago.
I need to create random word/names with random.choice(alphabet) for many of my games in repl,
but it is a pain to type it out, and make uppercase versions, consonants/vowels only, etc.
Is there a built-in or importable way to get a pre-made one in python?

The string module provides several (English-centric) values:
>>> import string
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.digits
'0123456789'
You'll have to create your own vowel/consonant lists, as well as lists for other languages.
Given how short the list of vowels is, vowels and consonants aren't too painful:
>>> vowels = set("aeiou")
>>> set(string.ascii_lowercase).difference(vowels)
{'b', 'f', 'v', 'q', 's', 'w', 'y', 'l', 'g', 'j', 'z', 'c', 'h', 'p', 'x', 'd', 'm', 'n', 't', 'k', 'r'}

Related

Using .join() function on a set incorrectly reorders it [duplicate]

This question already has answers here:
Converting a list to a set changes element order
(16 answers)
Closed 3 years ago.
I have a set of characters (x) that is ordered as I need it:
{'a',
'b',
'c',
'd',
'e',
'f',
'g',
'h',
'i',
'j',
'k',
'l',
'm',
'n',
'o',
'p',
'q',
'r',
's',
't',
'u',
'v',
'w',
'x',
'y',
'z'}
However, when I attempt to convert these back to a string using the .join() function:
return ' '.join(x)
The characters are being randomly reordered:
'c g e w i z n t l a q h p d f v m k b x u r j o y'
Any ideas as to what's going on here?
Sets don't "promise" to maintain order, sometimes they do, but they shouldn't be used with a dependency on it. Furthermore, consider using the following:
alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
Then:
return " ".join(alpha)
However, if you only care about it being in alphabetical and want to use a set you can force it to be sorted before using the join function...
return " ".join(sorted(x))
Good luck!
Sets and dictionaries are unordered (pre Python 3.7). Their exact implementation involves hashtables and can be a little complicated. However, suffice it to say that the order you put elements into the set does not determine the order they are stored.
You can use OrderedDict or you can convert the set to a list, sort, and go from there.

How to convert a string to a list? [duplicate]

This question already has answers here:
How to create a list with the characters of a string? [duplicate]
(5 answers)
Closed 7 years ago.
If I have a string:
a = 'hello'
How do I convert it into a list?
a = ['h', 'e', 'l', 'l', 'o']
A string is an iterable, and a list can be constructed from an iterable. So all you need is
a = list(a)
print(a)
Output:
['h', 'e', 'l', 'l', 'o']
Tried to do it differently
Code:
map(None,"sart")#for python 2.x
#list(map(None,"sart")) for python 3.x
Output:
['s', 'a', 'r', 't']

How to count the letters in a word? [duplicate]

This question already has answers here:
Letter Count on a string
(12 answers)
Closed 5 years ago.
I am trying to make a Python script which counts the amount of letters in a randomly chosen word for my Hangman game.
I already looked around on the web, but most thing I could find was count specific letters in a word. After more looking around I ended up with this, which does not work for some reason. If someone could point out the errors, that'd be greatly appreciated.
wordList = ["Tree", "Fish", "Monkey"]
wordChosen = random.choice(wordList)
wordCounter = wordChosen.lower().count['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
print(wordCounter)
Are you looking for collections.Counter?
>>> import collections
>>> print(collections.Counter("Monkey"))
Counter({'M': 1, 'y': 1, 'k': 1, 'o': 1, 'n': 1, 'e': 1})
>>> print(collections.Counter("Tree"))
Counter({'e': 2, 'T': 1, 'r': 1})
>>> c = collections.Counter("Tree")
>>> print("The word 'Tree' has {} distinct letters".format(len(c)))
The word 'Tree' has 3 distinct letters
>>> print("The word 'Tree' has {} instances of the letter 'e'".format(c['e']))
The word 'Tree' has 2 instances of the letter 'e'
First off, your code contains an error that is rather important to understand:
wordChosen.lower().count['a', 'b'] #...
count is a function and so it requires you to surround its parameters with parentheses and not square brackets!
Next you should try to refer to Python Documentation when using a function for the first time. That should help you understand why your approach will not work.
Now to address your problem. If you want to count the number of letters in your string use len(wordChosen) which counts the total number of characters in the string.
If you want to count the frequencies of each letter a few methods have already been suggested. Here is one more using a dictionary:
import string
LetterFreq={}
for letter in string.ascii_lowercase:
LetterFreq[letter] = 0
for letter in wordChosen.lower():
LetterFreq[letter] += 1
This has the nice perk of defaulting all letters not present in the word to a frequency of 0 :)
Hope this helps!
Problem:The count method only takes in one argument and you are trying to pass a whole list.
Solution:Simply iterate over all the letters, then test if they are in the string before you print them and their amount.
import random
wordList = ["Tree", "Fish", "Monkey"]
wordChosen = random.choice(wordList)
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
for letter in letters:
if letter in wordChosen.lower():
amount = str(wordChosen.lower().count(letter))
print(letter + " : " + amount)
Result:If the random word chosen is "Tree":
e : 2
r : 1
t : 1
Conclusion:Using collections is definitely a more effective method, but I believe the way I have shown above creates more of the output you were looking for.

an elegant way to concatenate a list of chars in a string in Python [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I optimally concat a list of chars to a string?
I have a list of chars:
['h', 'e', 'l', 'l', 'o']
Is there a way to concatenate the elements of such list in a string 'hello' that does not require c-like 'for' loop? Thanks.
This is the usual way of concatenating strings in Python:
''.join(list_of_chars)
In fact, that's the recommended way - for readability and efficiency reasons. For example:
''.join(['h', 'e', 'l', 'l', 'o'])
=> 'hello'
str.join
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
>>> ''.join(_)
'hello'
It's effectively:
from operator import add
reduce(add, ['h', 'e', 'l', 'l', 'o'])
But optimised for strings, it also only allows strings, otherwise it raises a TypeError
Yes. Use str.join
>>> chars = ['h', 'e', 'l', 'l', 'o']
>>> ''.join(chars)
'hello'

How to convert a string that has newline characters in it into a list in Python? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
split a string in python
I want to change this:
str = 'blue\norange\nyellow\npink\nblack'
to this:
list = ['blue','orange', 'yellow', 'pink', 'black']
I tried some for and while loops and have not been able to do it. I just want the newline character to be removed while triggering to make the next element. I was told to use:
list(str)
which gives
['b', 'l', 'u', 'e', '\n', 'o', 'r', 'a', 'n', 'g', 'e', '\n', 'y', 'e', 'l', 'l', 'o', 'w', '\n', 'p', 'i', 'n', 'k', '\n', 'b', 'l', 'a', 'c', 'k']
After this I use .remove() but only one '\n' is removed and the code gets more complicated to spell the colors.
You want your_str.splitlines(), or possibly just your_str.split('\n')
Using a for loop -- for instructional use only:
out = []
buff = []
for c in your_str:
if c == '\n':
out.append(''.join(buff))
buff = []
else:
buff.append(c)
else:
if buff:
out.append(''.join(buff))
print out

Categories

Resources