Quanti Monati
Quanti Monati

Reputation: 811

String contains \n and it leads to an ERROR

Actual code:

from selenium import webdriver

driver = webdriver.Chrome()
driver.get("https://htmlcompressor.com/compressor/")

two_str = "string_one\nstring_two"
driver.execute_script("document.getElementById('code').value = '%s';" % two_str)

Here is the error itself:

enter image description here As you can see, variable two_str contains "\n" (new line separator). And its presence leads to an error. But if its removed - everything works perfectly.

How to solve this problem?

P.S. I need to have a string with "\n" new line separator.

Upvotes: 0

Views: 392

Answers (2)

Corey Goldberg
Corey Goldberg

Reputation: 60644

use raw strings so the backslash doesn't get used as an escape char.

so change:

two_str = "string_one\nstring_two"

to

two_str = r"string_one\nstring_two"

Upvotes: 1

jdavid05
jdavid05

Reputation: 245

Use '\\n' to start a new line in a string. The first \ tells Python to read the second \ as part of the string.

string = "\\n"
print string

returns "\n"

Upvotes: 1

Related Questions