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.
If you want to add a string to the end of a string variable, use the += operator.
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.
Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator.
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.
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')
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With