Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

How can I write some text to the end of a line in a multiple-line string in python, without knowing slice numbers? Here's 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'm clear.

like image 824
uncleshelby Avatar asked Jan 12 '12 04:01

uncleshelby


People also ask

How do I add text to the end of a string in Python?

If you want to add a string to the end of a string variable, use the += operator.

How do you add a string at the end of each line in Python?

Explanation: To append text at end of current line use 'A' command. It appends the text at line extreme. Explanation: To replace a single character based on cursor location, 'r' command is used. To replace a single character, type 'r' followed by the character that replaces it.

How do you add a string to the end of a string?

Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator.

How do you add a space at the end of a line in Python?

Use the str. ljust() method to add spaces to the end of a string, e.g. result = my_str. ljust(6, ' ') . The ljust method takes the total width of the string and a fill character and pads the end of the string to the specified width with the provided fill character.


2 Answers

If the string is relatively small, I'd use str.split('\n') to break it into a list of strings. Then change the string you want, and the join the list:

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

Also, if you can identify uniquely how the line you want to append to ends, you can use replace. For instance, if the line ends with x, then you could do

mystr.replace('x\n', 'x extra extra stuff\n')
like image 103
thesamet Avatar answered Sep 28 '22 16:09

thesamet


First of all, strings are immutable so you will have to build a new string. Use the method splitlines on mystring object (so that you don't have to explicitly specify the line-end char) and then join them into a new string however 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
like image 32
wim Avatar answered Sep 28 '22 15:09

wim