Beginner's question about string's join() method

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Macygasp

    Beginner's question about string's join() method

    Hi,

    Can anybody tell me why and how this is working:
    >>','.join(str( a) for a in range(0,10))
    '0,1,2,3,4,5,6, 7,8,9'

    I find this a little weird because join takes a sequence as argument;
    so, it means that somehow, from the "str(a) ... " expression, a
    sequence can be generated.

    If I write this:
    >>(str(a) for a in range(0,10))
    <generator object at 0x7f62d2e4d758>
    it seems i'm getting a generator.

    Can anybody explain this to me, please?

    Thanks in advance.
  • Diez B. Roggisch

    #2
    Re: Beginner's question about string's join() method

    Macygasp wrote:
    Hi,
    >
    Can anybody tell me why and how this is working:
    >
    >>>','.join(str (a) for a in range(0,10))
    '0,1,2,3,4,5,6, 7,8,9'
    >
    I find this a little weird because join takes a sequence as argument;
    so, it means that somehow, from the "str(a) ... " expression, a
    sequence can be generated.
    >
    If I write this:
    >>>(str(a) for a in range(0,10))
    <generator object at 0x7f62d2e4d758>
    it seems i'm getting a generator.
    >
    Can anybody explain this to me, please?
    string.join takes an iterable. A generator is an iterable. Expressions of
    the form "<expfor <varsin <iterable>" are called "generator
    expressions", and yield a generator.

    Thus your code works.

    Diez

    Comment

    • Macygasp

      #3
      Re: Beginner's question about string's join() method

      On Aug 29, 3:51 pm, "Diez B. Roggisch" <de...@nospam.w eb.dewrote:
      Macygasp wrote:
      Hi,
      >
      Can anybody tell me why and how this is working:
      >
      >>','.join(str( a) for a in range(0,10))
      '0,1,2,3,4,5,6, 7,8,9'
      >
      I find this a little weird because join takes a sequence as argument;
      so, it means that somehow, from the "str(a) ... " expression, a
      sequence can be generated.
      >
      If I write this:
      >>(str(a) for a in range(0,10))
      <generator object at 0x7f62d2e4d758>
      it seems i'm getting a generator.
      >
      Can anybody explain this to me, please?
      >
      string.join takes an iterable. A generator is an iterable. Expressions of
      the form "<expfor <varsin <iterable>" are called "generator
      expressions", and yield a generator.
      >
      Thus your code works.


      Thanks, that's what I wanted to know.

      >
      Diez

      Comment

      Working...