Is there a possibility to extract single letters out of a string that the user of the program defines in python? For example i want to extract the single letters of this string:
x = raw_input["Letters i want to extract"]
asked May 8, 2013 at 23:38
1
A string is a sequence in Python the indexing starts from zero. To get a specific element or [character] of a string just use the following:
>>> x = "This is a string"
>>> first_letter = x[0]
>>> second_letter = x[1]
>>> last_letter = x[-1]
>>> print first_letter
T
>>> print last_letter
g
>>>
You can also loop through it very easily like so:
>>> for index, letter in enumerate[x]:
print index, letter
0 T
1 h
2 i
3 s
4
5 i
6 s
7
8 a
9
10 s
11 t
12 r
13 i
14 n
15 g
>>>
answered May 9, 2013 at 0:27
>>> s = 'test'
>>> s[0]
't'
>>> list[s]
['t', 'e', 's', 't']
>>> for ch in s:
... print ch
...
t
e
s
t
answered May 8, 2013 at 23:42
Bibhas DebnathBibhas Debnath
14.2k17 gold badges67 silver badges96 bronze badges
A variable has a name and a value.
A dictionary is a collection of names associated with values. So, for your purposes you might be able to make a dictionary and treat it as "a collection of variables".
For example, if you want the "single variables" for each letter in x to be counters, then you could use this code:
def stats[]:
x = raw_input["Letters i want to extract: "]
data = raw_input["Text I want to do some stats on: "]
# make a dictionary of letters in x
d = {}
for chr in x:
d[chr] = 0 # initialize counter
# collect stats
for item in data:
if item in d:
d[item] += 1
# show results in a couple of ways
print "The full tally: %r" % d
for chr in x:
print "There were %d occurrences of %c in the text" % [d[chr], chr]
Here's an example run.
>>> stats[] Letters i want to extract: bell Text I want to do some stats on: hello world The full tally: {'b': 0, 'e': 1, 'l': 3} There were 0 occurrences of b in the text There were 1 occurrences of e in the text There were 3 occurrences of l in the text There were 3 occurrences of l in the text
answered May 9, 2013 at 0:05
azhreiazhrei
2,29316 silver badges18 bronze badges
1
x = raw_input["Letters i want to extract"]
for i in x:
print i
#or do whatever you please
I think this is what your looking for. The code snip-it iterates through the string and outputs each letter. Instead of printing you could do what ever you would like.
You can also access each letter individuality through the syntax x[index_value].
ie.
x[0] would yield 'L'
x[1] would yield 'e'
answered May 8, 2013 at 23:42
agcontiagconti
17.2k15 gold badges77 silver badges113 bronze badges
1
You can use a for loop like this
x = raw_input["Letters i want to extract"]
for ch in x:
print x
You can also get individual characters like this
x[0] # first character
x[1] # second character
You can convert to a list like this
char_list = list[x]
answered May 8, 2013 at 23:41
John La RooyJohn La Rooy
286k51 gold badges358 silver badges498 bronze badges