git.net

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

String slices


On 09Aug2019 22:28, Paul St George <email at paulstgeorge.com> wrote:
>On 09/08/2019 16:29, Rhodri James wrote:
>>The 'sep="\n"' parameter to print() means "put a newline between each 
>>item."? So don't do that.? Put the newlines you do want in explicitly, 
>>or use separate calls to print():
>>
>>(I'm abbreviating because I really can't be bothered to type that 
>>much :-)
>>
>>? print("X:", thing[0],
>>??????? "\nY:", thing[1],
>>??????? "\nZ:", thing[2],
>>??????? file=outstream)
>>
>>or
>>
>>? print("X:", thing[0], file=outstream)
>>? print("Y:", thing[1], file=outstream)
>>? print("Z:", thing[2], file=outstream)
>>
>>I would probably use the latter, but it's just a matter of personal 
>>preference.
>>
>>(Actually I would probably use outstream.write() and do my own 
>>formatting, but let's not get side-tracked ;-)
>>
>So, I am going with your second suggestion (see below) but I would love 
>to hear your outstream.write() side-track!

I am not Rhodri James, but you can just write strings to text files:

  outstream.write("X: ")  # note, includes the space separator
  outstream.write(str(thing[0]))
  outstring.write("\n")

print() is convenient, because it calls str() on any non-str argument 
for you, and it does the space separators and newline line ending (both 
overridable).

You can see the above is rather verbose. But it does let you control 
exactly what gets written, _if_ the print separators and endings are 
causing you inconvenience.

Personally, for text output, I use print unless there's some compelling 
reason not to (such as transcribing a data structure precisely, not 
wanting unexpected spaces and newlines; if I were hand transcribing JSON 
or XML or HTML or the like).

Cheers,
Cameron Simpson <cs at cskk.id.au>