简体   繁体   English

将行从BASH转换为Python

[英]Convert line from BASH to Python

I have a line in a BASH script that looks like 我在BASH脚本中有一行看起来像

 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? 那行在Python中会是什么样子?

bash don't interpret escape characters in string so if we write "\\n" it prints it as it is. bash不会解释字符串中的转义字符,因此,如果我们编写“ \\ n”,它将按原样打印。 To avoid this we use $'\\n' for line break. 为了避免这种情况,我们使用$'\\ n'作为换行符。

In short its for line break in bash.

ANSI C quoting : ANSI C引用

Words of the form $'string' are treated specially. $'string'形式的单词经过特殊处理。 The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard. 该单词扩展为字符串,并按ANSI C标准的规定替换反斜杠转义字符。

So, $'\\n' in bash is "\\n" in Python. 因此,bash中的$'\\n'在Python中为"\\n"

In bash, you can stick strings together. 在bash中,您可以将字符串粘在一起。 "a""b" is the same as "ab" . "a""b""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. 三个是普通的双引号,并且在两个之间有两个ANSI C引用。 In Python, you can do almost the same, but with a space in between: "a" "b" is equivalent to "ab" . 在Python中,您可以执行几乎相同的操作,但是之间必须有一个空格: "a" "b"等同于"ab" The literal translation would thus be be 直译是

var = "stuff=1" "\\n" "more_stuff=1" "\\n" "even_more_stuff='abc'" 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'" var =“ stuff = 1 \\ nmore_stuff = 1 \\ neven_more_stuff ='abc'”

bash and zsh interprets $'\\n' as a new line bash和zsh将$'\\ n'解释为新行

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 在python中

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

output 输出

stuff=1
more_stuff=1
even_more_stuff='abc'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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