是否有可能从程序的用户在python中定义的字符串中提取单个字母?比如我想提取该字符串的单个字母:从python中的字符串中提取单个字母
x = raw_input("Letters i want to extract")
是否有可能从程序的用户在python中定义的字符串中提取单个字母?比如我想提取该字符串的单个字母:从python中的字符串中提取单个字母
x = raw_input("Letters i want to extract")
您可以使用一个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)
>>> s = 'test'
>>> s[0]
't'
>>> list(s)
['t', 'e', 's', 't']
>>> for ch in s:
... print ch
...
t
e
s
t
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'
好抓;我更新了我的答案。 – agconti 2013-05-09 00:45:09
变量有一个名称和一个值。
字典是与值相关联的名称的集合。因此,出于您的目的,您可能可以创建一本字典并将其视为“一组变量”。
例如,如果你想要的“单变量” 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
我发誓OP最初被要求能够将'x'的元素当作变量来处理 - 因此对这个答案有偏见。不知道为什么编辑历史的帖子不再显示这个! – azhrei 2013-05-09 00:54:59
字符串是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
>>>
'在x' single_letter? – squiguy 2013-05-08 23:41:11