How can I modify this code to add a punctuation mark at the end of the sentence without a space?

Viewed 26

This code:

lst = range(59, 125)

    df2 = df2.rename(columns={col: col+'.'
                        for idx, col in enumerate(df2.columns)
                        if idx in lst})

adds a punctuation mark at the end of every title in a column. But it adds a spacemark just before the punctuation mark. E.g. Code turns:

I would never do that

to:

I would never do that .

And I want:

I would never do that.

ALSO

Some titles have a question mark at the end and this code adds a punctuation mark after it. How can I modify or add to my code to not place a punctuation marks after question marks?

E.g. Code turns:

Are you satisfied?

to:

Are you satisfied?.

2 Answers

Try adding rstrip() function to your column. This removes right trialing withe spaces.

For not adding the point after interrogation, you should add an if exception to your code:

 lst = range(59, 125)

    df2 = df2.rename(columns={col: col.rstrip() +'.'
                        for idx, col in enumerate(df2.columns)
                        if idx in lst and col.rstrip()[-1] != '?'})

Probably because you already have a space in each column's name. Try this to strip it by using

df2 = df2.rename(columns={col: col.strip()+'.'
                        for idx, col in enumerate(df2.columns)
                        if idx in lst})
Related