Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a set filled with letters from the alphabet in python

Tags:

python

I am trying to create a set of the letters from the alphabet and I'm not sure why the code is not working. Python gives me an error saying that the "global name 'a' is not defined." Any ideas? Thank you in advance.

  s = set()
  s = {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}
like image 705
user3495872 Avatar asked May 19 '14 21:05

user3495872


People also ask

How do you assign each letter of the alphabet to a number in Python?

Use the ord() Function to Convert Letters to Numbers in Python. The ord() function in Python is utilized to return the Unicode , or in this case, the ASCII value of a given letter of the alphabet. We will apply the ord() function to the letters and subtract 96 to get the accurate ASCII value.


2 Answers

a, b, ... on their own are not strings, they are names. Python strings must be enclosed in single quotes ('a'), double quotes ("a") or triple quotes ("""a""" or '''a'''). So, the correct version of your code would be:

# s = set() - this is useless, the next line is already creating a set
s = {'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'}

Having said that, a much cleaner way of doing this is to use Python's built-in set and string.ascii_lowercase like so:

import string
s = set(string.ascii_lowercase)
like image 198
s16h Avatar answered Sep 23 '22 23:09

s16h


try this

import string
s = set(string.ascii_lowercase)
like image 21
lenik Avatar answered Sep 24 '22 23:09

lenik