forward slash in string literal behaves unexpectedly

Viewed 55

why do S1 and S2 behave differently with respect to apostrophe location?

S1="1/282/03/10"
S2="4/107/03/10"
R1="".join({"N\'" ,S1,"\'" })
R2="".join({"N\'" ,S2,"\'" })

Outputs:

"N''1/282/03/10"    //R1 
"N'4/107/03/10'"    //R2
2 Answers

That's because you are using set.

set is a collection which is unordered and unindexed.

So you have to use the following code to get the desired results,

S1 = "1/282/03/10"
S2 = "4/107/03/10"
R1 = "".join(["N\'", S1, "\'"])
R2 = "".join(["N\'", S2, "\'"])

print(R1)
print(R2)

Output:

N'1/282/03/10'
N'4/107/03/10'

The reason is you wrap "\'",S1,"'\" in a set.

set is an unordered collection.

To avoid the above issue use list or tuple.

R1 = "".join(["N\'", S1, "\'"])
R2 = "".join(["N\'", S2, "\'"])

#tuple equivalent is
R1 = "".join(("N\'", S1, "\'"))
R2 = "".join(("N\'", S2, "\'"))

You can use .format here you don't even need to use list or tuple.

R1="N'{}'".format(S1)
R2="N'{}'".format(S2)

You can also use this.

R1 = "N\'" + S1 + "\'"
R2 = "N\'" + S2 + "\'"
Related