在python中从字符串中提取单个字母

时间:2013-05-08 23:38:27

标签: python

是否有可能从程序用户在python中定义的字符串中提取单个字母?例如,我想提取该字符串的单个字母:

     x = raw_input("Letters i want to extract")

5 个答案:

答案 0 :(得分:2)

字符串是Python中的一个序列,索引从零开始。要获取字符串的特定元素或(字符),请使用以下命令:

>>> 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
>>> 

您也可以像这样轻松地遍历它:

>>> 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
>>> 

答案 1 :(得分:1)

>>> s = 'test'
>>> s[0]
't'
>>> list(s)
['t', 'e', 's', 't']
>>> for ch in s:
...     print ch
...
t
e
s
t

答案 2 :(得分:1)

x = raw_input(“我要提取的信件”)

for i in x:
    print i 
    #or do whatever you please

我认为这就是你要找的东西。代码片段 - 它遍历字符串并输出每个字母。而不是印刷,你可以做任何你想做的事情。

您还可以通过语法x [index_value]访问每个字母的个性。

x[0] would yield 'L'
x[1] would yield 'e'

答案 3 :(得分:1)

变量具有名称和值。

字典是与值相关联的名称的集合。因此,出于您的目的,您可以制作字典并将其视为“变量集合”。

例如,如果您希望x中每个字母的“单个变量”为计数器,那么您可以使用此代码:

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)

这是一个示例运行。

>>> 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

答案 4 :(得分:0)

您可以像这样使用for循环

x = raw_input("Letters i want to extract")
for ch in x:
    print x

你也可以获得这样的个人角色

x[0] # first character
x[1] # second character

您可以转换为此类列表

char_list = list(x)