How to add text to the end of a line in a line? - Python

How can I write text at the end of a line in a line with multiple lines in python without knowing the fragment numbers? Here is an example:

mystring=""" This is a string. This is the second Line. #How to append to the end of this line, without slicing? This is the third line.""" 

I hope I get it.

+4
source share
2 answers

If the string is relatively small, I would use str.split('\n') to split it into a list of strings. Then change the desired line and concatenate the list:

 l = mystr.split('\n') l[2] += ' extra text' mystr = '\n'.join(l) 

In addition, if you can uniquely identify how the string you want to add to the ends, you can use replace . For example, if the line ends with x , you can do

 mystr.replace('x\n', 'x extra extra stuff\n') 
+6
source

First of all, the lines are immutable, so you will need to create a new line. Use the splitlines method on the mystring object (so you don't need to explicitly indicate the end of the char string), and then append them to the new line as you wish.

 >>> mystring = """ ... a ... b ... c""" >>> print mystring a b c >>> mystring_lines = mystring.splitlines() >>> mystring_lines[2] += ' SPAM' >>> print '\n'.join(mystring_lines) a b SPAM c 
+1
source

Source: https://habr.com/ru/post/1390573/


All Articles