String Line

String Line
How to take a large Python string and turn it into single line, Variable labeled strings?

For example-
a=”this is the example
this is line two”
into
a=’this is an example’
b=’this is line two’
and so on, i need it to this for up to 100 lines of sting, can it be done?

Are you certain that you want to have each line references by a separate distinctly-named variable? That’s doable, but doing it is a little tricky and dealing with all of those different variables while trying to using the result is awkward.

Typically what programs do in this situation is to break the large string into pieces at each end-of-line marker and place those pieces in a list. You can then access the individual line strings by using an index into the list, and you can easily walk through any number of the strings by using a ‘for’ loop. To do this, use the ‘split()’ method on the original large string, like this:

  large_string = ”’this is an
  example of a
  large string”’

  list_of_lines = large_string.split( ‘n’ )

list_of_lines is now this list:

  [ 'this is an', 'example of a', 'large string' ]

and you can access individual strings like this:

  print list_of_lines[ 2 ]    # prints ‘large string’

or do something with each string in turn:

  for line in list_of_lines:
      print line

how to tie a string line


You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

Comments are closed.