ToString

Pydoc Pydoc




Transforms every element in an input collection to a string.

Examples

Any non-string element can be converted to a string using standard Python functions and methods. Many I/O transforms, such as textio.WriteToText, expect their input elements to be strings.

Example 1: Key-value pairs to string

The following example converts a (key, value) pair into a string delimited by ','. You can specify a different delimiter using the delimiter argument.

import apache_beam as beam

with beam.Pipeline() as pipeline:
  plants = (
      pipeline
      | 'Garden plants' >> beam.Create([
          ('πŸ“', 'Strawberry'),
          ('πŸ₯•', 'Carrot'),
          ('πŸ†', 'Eggplant'),
          ('πŸ…', 'Tomato'),
          ('πŸ₯”', 'Potato'),
      ])
      | 'To string' >> beam.ToString.Kvs()
      | beam.Map(print)
  )

Output PCollection after ToString:

πŸ“,Strawberry
πŸ₯•,Carrot
πŸ†,Eggplant
πŸ…,Tomato
πŸ₯”,Potato
Run code now Run code now
View source code View source code




Example 2: Elements to string

The following example converts a dictionary into a string. The string output will be equivalent to str(element).

import apache_beam as beam

with beam.Pipeline() as pipeline:
  plant_lists = (
      pipeline
      | 'Garden plants' >> beam.Create([
          ['πŸ“', 'Strawberry', 'perennial'],
          ['πŸ₯•', 'Carrot', 'biennial'],
          ['πŸ†', 'Eggplant', 'perennial'],
          ['πŸ…', 'Tomato', 'annual'],
          ['πŸ₯”', 'Potato', 'perennial'],
      ])
      | 'To string' >> beam.ToString.Element()
      | beam.Map(print)
  )

Output PCollection after ToString:

['πŸ“', 'Strawberry', 'perennial']
['πŸ₯•', 'Carrot', 'biennial']
['πŸ†', 'Eggplant', 'perennial']
['πŸ…', 'Tomato', 'annual']
['πŸ₯”', 'Potato', 'perennial']
Run code now Run code now
View source code View source code




Example 3: Iterables to string

The following example converts an iterable, in this case a list of strings, into a string delimited by ','. You can specify a different delimiter using the delimiter argument. The string output will be equivalent to iterable.join(delimiter).

import apache_beam as beam

with beam.Pipeline() as pipeline:
  plants_csv = (
      pipeline
      | 'Garden plants' >> beam.Create([
          ['πŸ“', 'Strawberry', 'perennial'],
          ['πŸ₯•', 'Carrot', 'biennial'],
          ['πŸ†', 'Eggplant', 'perennial'],
          ['πŸ…', 'Tomato', 'annual'],
          ['πŸ₯”', 'Potato', 'perennial'],
      ])
      | 'To string' >> beam.ToString.Iterables()
      | beam.Map(print)
  )

Output PCollection after ToString:

πŸ“,Strawberry,perennial
πŸ₯•,Carrot,biennial
πŸ†,Eggplant,perennial
πŸ…,Tomato,annual
πŸ₯”,Potato,perennial
Run code now Run code now
View source code View source code




Pydoc Pydoc