2

I want to write something as one line such as:

Blah blah 123456 0.0000123

I used the below code:

value1 = 123456
value2 = 0.0000123
k = "Blah blah" + value1 +value2
File.write(k)
#outFile.write("Blah blah %s %s" % (value1 ,value2) )

The output is always:

Blah blah 123456
0.0000123
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
GigI
  • 51
  • 2
  • 9

4 Answers4

1

You have to convert your integers to strings (see this answer : Making a string out of a string and an integer in Python )

k = "Blah blah" + str(value1) + str(value2)

same thing with the %s formatters. The parameters should be str(variables), not just variables

Pac0
  • 21,465
  • 8
  • 65
  • 74
  • I did convert both the values to string @Pac0 – GigI Jun 15 '17 at 19:02
  • @Gigl in this case, you have to use `.strip()` additionaly, as you and others have pointed out. However, I'm curious about why you have a trailing newline. Which operating system do you use ? – Pac0 Jun 16 '17 at 15:33
1

Integers when concatenated with strings have an assumed endline character afterwards. To remedy this problem, you can convert these ints to strings before concatenating all of them. You can do this with the str() function which is written about here: https://docs.python.org/2/library/functions.html

JoshKopen
  • 940
  • 1
  • 8
  • 22
1

You need to convert them to strings and strip them to remove any tailing characters.

str(value1).strip() + str(value2).strip()
be_good_do_good
  • 4,311
  • 3
  • 28
  • 42
0

Here is how I would do it:

>>> value1 = '123456'
>>> value2 = '0.000123'
>>> k = "Blah blah " + value1 + " " + value2
>>> print k
Blah blah 123456 0.000123

Do note the space after the second "blah", and the space between value1 and value2 in line 3.

You have to make sure you value1 and value2 are set as strings. You can also do it like this:

>>> value1 = 123456
>>> value2 = 0.000123
>>> str(value1)
>>> str(value2)
Brandon Molyneaux
  • 1,543
  • 2
  • 12
  • 23
  • I tried this - converted both values to string. It just becomes Blah blah 123456 \n 0.0000123 – GigI Jun 15 '17 at 19:02
  • Try doing this: `file_name = 'text_file.txt' f = open(file_name, 'w') value1 = '123456' value2 = '0.0000123' k = "Blah blah " + value1 + ' ' + value2 f.write(k) f.close()`. I just tried it and it gave me the output you're looking for. Look through your code to see if you don't have a \n anywhere in your output. – Brandon Molyneaux Jun 15 '17 at 19:12
  • Thanks! It worked with str(value).strip(), I can try with this too! – GigI Jun 15 '17 at 20:02