开发者

simple question on python's split

开发者 https://www.devze.com 2023-02-14 13:24 出处:网络
Not sure why last print is off? Please see comments for specific question john = [\'john doe\', 44, 32000]

Not sure why last print is off? Please see comments for specific question

 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 开发者_C百科p[0].split():
        print('--> ', x[0]) 

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


  1. p[0].split() returns a list of strings
  2. for x in... deals with each string in the list
  3. x[0] is therefore the first character in the string

you probably want to get rid of the subscript after 'x'.


Use it like this

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) 


As you said, p[0].split() gives you ['john', 'doe']. In your loop, x refers in turn to the elements of this list, "john" and "doe". x[0] refers to the first item in either of these-- the first character in the string.

0

精彩评论

暂无评论...
验证码 换一张
取 消