A
A
Alexey Poloz2017-03-27 23:24:24
Python
Alexey Poloz, 2017-03-27 23:24:24

Python How to put a space before and after all characters (not letters) in a string?

We need the most optimal code, since there are a lot of lines
. For example: 'hello. 123' -> 'hello . 123'

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
longclaps, 2017-03-28
@kosyachniy

import re
s = 'привет. 123,56    !  78'
print(re.sub(r'([.,!?])', r' \1 ', s))  # добавляет пробелы
print(re.sub(r' *([.,!?]) *', r' \1 ', s))  # оставляет ровно по одному пробелу до/после

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question