Skip to content

Commit 2fa7eeb

Browse files
Escape single quotes
1 parent 597e6c5 commit 2fa7eeb

File tree

2 files changed

+16
-22
lines changed

2 files changed

+16
-22
lines changed

pandas/io/formats/printing.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,7 @@ def pprint_thing(
202202
def as_escaped_string(
203203
thing: Any, escape_chars: EscapeChars | None = escape_chars
204204
) -> str:
205-
translate = {"\t": r"\t", "\n": r"\n", "\r": r"\r", "'": ""}
205+
translate = {"\t": r"\t", "\n": r"\n", "\r": r"\r", "'": r"\'"}
206206
if isinstance(escape_chars, Mapping):
207207
if default_escapes:
208208
translate.update(escape_chars)

pandas/tests/io/formats/test_printing.py

Lines changed: 15 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2,33 +2,27 @@
22
# functions, not the general printing of pandas objects.
33
from collections.abc import Mapping
44
import string
5-
import ast
5+
import pytest
66
import pandas._config.config as cf
77
import pandas as pd
88
from pandas.io.formats import printing
99

1010

11-
def test_formatted_index_names():
12-
# Test cases: (input index names, expected formatted index names as lists)
13-
test_cases = [
14-
(["'a", "b"], ['a', 'b']), # Remove leading quote
15-
(["test's", "b"], ['tests', 'b']), # Remove apostrophe
16-
(["'test'", "b"], ['test', 'b']), # Remove surrounding quotes
17-
(["test","'b"], ["test",'b']), # Remove single quote
18-
(["'test\n'", "b"], ['test\n', 'b']) # Remove quotes, preserve newline
19-
]
20-
21-
for input_names, expected_names in test_cases:
22-
# Create DataFrame with specified index names
23-
df = pd.DataFrame(
24-
{name: [1, 2, 3] for name in input_names}
11+
@pytest.mark.parametrize("input_names, expected_names", [
12+
(["'a", "b"], ["\'a", "b"]), # Escape leading quote
13+
(["test's", "b"], ["test\'s", "b"]), # Escape apostrophe
14+
(["'test'", "b"], ["\'test\'", "b"]), # Escape surrounding quotes
15+
(["test","b'"], ["test","b\'"]), # Escape single quote
16+
(["'test\n'", "b"], ["\'test\n\'", "b"]) # Escape and preserve newline
17+
])
18+
def test_formatted_index_names(input_names, expected_names):
19+
# Create DataFrame with specified index names
20+
df = pd.DataFrame(
21+
{name: [1, 2, 3] for name in input_names}
2522
).set_index(input_names)
26-
index_names_str = df.index.names.__str__()
27-
28-
formatted_names = ast.literal_eval(index_names_str)
29-
30-
# Compare the formatted names with the expected names
31-
assert formatted_names == expected_names
23+
formatted_names = df.index.names
24+
25+
assert formatted_names == expected_names
3226

3327

3428
def test_adjoin():

0 commit comments

Comments
 (0)