简体   繁体   中英

Convert line from BASH to Python

I have a line in a BASH script that looks like

 VAR="stuff=1"$'\n'"more_stuff=1"$'\n'"even_more_stuff='abc'"

I have two questions, what does

 "$'\n'

do?

and What would that line look like in Python?

bash don't interpret escape characters in string so if we write "\\n" it prints it as it is. To avoid this we use $'\\n' for line break.

In short its for line break in bash.

ANSI C quoting :

Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard.

So, $'\\n' in bash is "\\n" in Python.

In bash, you can stick strings together. "a""b" is the same as "ab" . In your line, to allow for different ways of quoting, you're sticking together five different strings; three are normal double-quoted ones, and in between there are two ANSI C quoted. In Python, you can do almost the same, but with a space in between: "a" "b" is equivalent to "ab" . The literal translation would thus be be

var = "stuff=1" "\\n" "more_stuff=1" "\\n" "even_more_stuff='abc'"

but you'd normally write it as

var = "stuff=1\\nmore_stuff=1\\neven_more_stuff='abc'"

bash and zsh interprets $'\\n' as a new line

VAR="stuff=1"$'\n'"more_stuff=1"$'\n'"even_more_stuff='abc'"
echo "$VAR"

output

stuff=1
more_stuff=1
even_more_stuff='abc'

in python

VAR = "stuff=1\nmore_stuff=1\neven_more_stuff='abc'"
print VAR

output

stuff=1
more_stuff=1
even_more_stuff='abc'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM