将字符序列转换为特殊字符

时间:2016-10-10 18:47:23

标签: javascript json

我有一个包含多个转义字符的相当大的字符串(想想\ n,\ xB7,...)。这些“特殊字符”作为字符序列存储在字符串中,而不是实际的特殊字符。简而言之,我需要一种方法将字符序列转换为它们所代表的实际特殊字符。

以下是我目前创建的一些示例:

from math import sqrt
from turtle import Turtle, Screen

SCALE = 300
ITERATIONS = 7

def draw_circle(turtle):
    turtle.goto(0, -SCALE)
    turtle.pendown()
    turtle.circle(SCALE)
    turtle.penup()

def inscribe_circle(turtle, sides, edge_length):
    turtle.goto(0, -SCALE)
    turtle.setheading(0)
    turtle.left(180 / sides)
    turtle.pendown()
    for _ in range(sides):
        turtle.forward(edge_length * SCALE)
        turtle.left(360 / sides)
    turtle.penup()

# based on code and analysis from http://www.craig-wood.com/nick/articles/pi-archimedes/
def pi_archimedes(turtle, n):
    """ Calculate n iterations of Archimedes PI recurrence relation """

    polygon_edge_length_squared = 2.0
    polygon_edge_length = sqrt(polygon_edge_length_squared)
    polygon_sides = 4

    inscribe_circle(turtle, polygon_sides, polygon_edge_length)
    print(polygon_sides * polygon_edge_length / 2)

    for _ in range(n - 1):
        polygon_sides *= 2
        polygon_edge_length_squared = 2 - 2 * sqrt(1 - polygon_edge_length_squared / 4)
        polygon_edge_length = sqrt(polygon_edge_length_squared)
        inscribe_circle(turtle, polygon_sides, polygon_edge_length)
        print(polygon_sides * polygon_edge_length / 2)

yertle = Turtle()
yertle.penup()

draw_circle(yertle)

pi_archimedes(yertle, ITERATIONS)

yertle.hideturtle()

Screen().exitonclick()

我需要替换所有字符序列,而不仅仅是\ n:

var seq = "\n"
//outputs "
//         "

seq = "\\n" 
// outputs "\n"

seq.replace(/\\\\/g, "\\") 
// outputs "\n"

0 个答案:

没有答案