关于python分裂的简单问题

时间:2011-03-01 03:26:08

标签: python string split

不确定为什么最后一次打印已关闭?请参阅具体问题的评论

 john = ['john doe', 44, 32000]

jane = ['jane doe', 23, 12000]

people = [john, jane]

for p in people: 
    #===========================================================================
    # p[0] prints "john doe" as expected
    # p[0].split() prints ['john', 'doe'] as expected
    # p[0].split()[0] prints "john" and "jane" as expected
    #===========================================================================
    for x in p[0].split():
        print('--> ', x[0]) 

    # prints "j","d" - not sure why
    # expected "john" and "jane"

3 个答案:

答案 0 :(得分:4)

  1. p [0] .split()返回字符串列表
  2. for x in ...处理列表中的每个字符串
  3. x [0]因此是字符串
  4. 中的第一个字符

    你可能想要摆脱'x'之后的下标。

答案 1 :(得分:0)

像这样使用

for p in people: 
    #===========================================================================
    # p[0] prints "john doe" as expected
    # p[0].split() prints ['john', 'doe'] as expected
    # p[0].split()[0] prints "john" and "jane" as expected
    #===========================================================================
    for x in p.split():
        print('--> ', x) 

答案 2 :(得分:0)

如你所说,p [0] .split()给你['john','doe']。在你的循环中,x又指向该列表的元素“john”和“doe”。 x [0]指的是其中任何一个中的第一项 - 字符串中的第一个字符。