How to replace multiple characters with a method replace()? Is there only one way to do this replace()? Or are there any better ways?
replace()
The symbols may look like this, for example -, +, /, ', ., &.
-
+
/
'
.
&
You can use re.suband put characters in a character class :
re.sub
import re re.sub('[-+/\'.&]', replace_with, input)
You can do this by using str.joinwith a generator expression (without importing any library) like:
str.join
>>> symbols = '/-+*' >>> replacewith = '.' >>> my_text = '3 / 2 - 4 + 6 * 9' # input string # replace char in string if symbol v >>> ''.join(replacewith if c in symbols else c for c in my_text) '3 . 2 . 4 . 6 . 9' # Output string with symbols replaced
# '7' -> 'A', '8' -> 'B' print('asdf7gh8jk'.replace('7', 'A').replace('8', 'B'))
, , :
string = 'abc' old = ['a', 'b', 'c'] new = ['A', 'B', 'C'] for o, n in zip(old, new): string = string.replace(o, n) print string >>> 'ABC'
Source: https://habr.com/ru/post/1663772/More articles:Custom UserStore for ASP.NET Core Identity - .netHow to clone and add multiple elements using jQuery? - javascriptHow do I unit test mapDispatchToProps in Redux? - unit-testingБлокировка в JavaScript и внутренних функциях - javascriptWhy is File.read ('/ path / to / file') not in Ruby docs? - ruby | fooobar.comAutomatically "test" Storybook - unit-testingHow to use activity with Android in React Native - androidОбрезать изображение с исправленным искажением в OpenCV (Python) - pythonРазбор JSON-формата с jq - jsonPerform LU decomposition without rotation in MATLAB - matrixAll Articles