How to Create String With Line Breaks in Python

How to create string with line breaks in Python?

Using triple-quotes

You can use the triple-quotes (""" or ''') to assign a string with line breaks:

string = """What would I do without your smart mouth?
Drawing me in, and you kicking me out
You've got my head spinning, no kidding, I can't pin you down
What's going on in that beautiful mind
I'm on your magical mystery ride
And I'm so dizzy, don't know what hit me, but I'll be alright"""

As explained by the documentation:

String literals can span multiple lines. One way is using triple-quotes: """...""" or '''...'''. End of lines are automatically included in the string [...]

Using \n

You can also explicitly use the newline character (\n) inside your string to create line breaks:

string = "What would I do without your smart mouth?\nDrawing me in, and you kicking me out\nYou've got my head spinning, no kidding, I can't pin you down\nWhat's going on in that beautiful mind\nI'm on your magical mystery ride\nAnd I'm so dizzy, don't know what hit me, but I'll be alright"

Python insert a line break in a string after character "X"

myString = '1X2X3X'
print (myString.replace ('X', 'X\n'))

Adding a line break in string variable

Your code runs well for me.
"But the resulting string looks like this" -> what's the way you show the string?

a = """"Asset Serial No;Depot"
"abc;111"""""

b = "<root>" + "\n"
for line in a.splitlines():
b = b + line.strip('""') + "\n"

b = b + "<root>"

print(b)

Sample Image

Add line break after every 20 characters and save result as a new string

You probably want to do something like this

inp = "A very very long string from user input"
new_input = ""
for i, letter in enumerate(inp):
if i % 20 == 0:
new_input += '\n'
new_input += letter

# this is just because at the beginning too a `\n` character gets added
new_input = new_input[1:]

How to do a line break in python?

Here it is,
learn about operators and formatting to print output

balance = float(raw_input("Enter the outstanding balance on your credit card: "))
annual_itst = float(raw_input("Enter the annual credit card interest rate as a decimal: "))
min_paymt_rate = float(raw_input("Enter the minimum monthly payment rate as a decimal: "))

remaining_balance = balance

for i in range(1,13):
min_monthly_paymt=min_paymt_rate*remaining_balance
inst_paid = (annual_itst / 12.0 )*remaining_balance
pcpl_paid = min_monthly_paymt - inst_paid
remaining_balance -= pcpl_paid
print "\n\n\n"
print "Month: {}".format(i), '\n',"Minimum monthly payment: $ {}".format(round(min_monthly_paymt, 2)), '\n',"Principle paid:$ ".format(round(pcpl_paid, 2)),'\n',"Remaining balance: $".format(round(remaining_balance, 2))

Split string in Python while keeping the line break inside the generated list

Split String using Regex findall()

import re

my_string = "This is a test.\nAlso\tthis"
my_list = re.findall(r"\S+|\n", my_string)

print(my_list)

How it Works:

  • "\S+": "\S" = non whitespace characters. "+" is a greed quantifier so it find any groups of non-whitespace characters aka words
  • "|": OR logic
  • "\n": Find "\n" so it's returned as well in your list

Output:

['This', 'is', 'a', 'test.', '\n', 'Also', 'this']

How to add a line break in python?

You can print new line characters:

print('\n'*numlines)

Line Break in Python not working

If you remove the \ you got a line break. The \ is telling python to ignore the line break. The triple quote method lets you enter string on multiple lines. If you want to enter the string on one line you can use \n to get line breaks.

Creating a newline in a string after 20 characters at the end of a word, Python

There may be better ways to do this but this seems to work:-

s = "A very long string which is definately more than 20 characters long"
offset = 0
try:
while True:
p = s.rindex(' ', offset, offset + 20)
s = s[:p] + '\n' + s[p + 1:]
offset = p
except ValueError:
pass

print(s)


Related Topics



Leave a reply



Submit