Tech C**P
14 subscribers
161 photos
9 videos
59 files
304 links
مدرس و برنامه نویس پایتون و لینوکس @alirezastack
Download Telegram
How to replace multiple characters in a string using python?

As you may already know there is a method for string called replace that replaces 1 character with a new given character:
'+98 21 445 54 12'.replace('+', '')
# output is 98 21 445 54 12

But what if you want to replace both + and [SPACE] inside of the string? The answer is simple just chain the methods:
'+98 21 445 54 12'.replace('+', '').replace(' ', '')

Here output would be 98214455412.

#python #string #replace #multiple_replacement
Tech C**P
How to replace multiple characters in a string using python? As you may already know there is a method for string called replace that replaces 1 character with a new given character: '+98 21 445 54 12'.replace('+', '') # output is 98 21 445 54 12 But…
If the replacements are going to be more in number, you can do this in this generic way:
strs, replacements = "abc&def#ghi", {"&": "\&", "#": "\#"}
print "".join([replacements.get(c, c) for c in strs])
# abc\&def\#ghi

#python #join #replace
In Pycharm I wrote something like below in multiple lines in the file:


method_name='get_account'


I wanted to add _v2 to all the method names, what I did was to use regex in PyCharm replace functionality. Press Command+R in order to open replace dialog. In the dialog there is an option called Regex, tick the checkbox in front of it and in find section write:


method_name='(.*)'


It will find all lines which has different names: .* and put that in a variable. (you can put something you have found in a variable by using parenthesis).

Now we can access the variable using $1. We now need to put the below code in replace section:


method_name='$1_v2'


The above code will put method name using $1 and the append _v2 to all the methods.


#pycharm #regex #find #replace
How to localize a UTC date?

import pytz
import datetime

date_format = '%Y-%m-%d %H:%M:%S'
dt = datetime.datetime.strptime('2018-12-12 00:00:00', date_format)
utc_tz = pytz.timezone('UTC')
utc_d = utc_tz.localize(dt)
teh_tz = pytz.timezone('Asia/Tehran')
dt = utc_d.astimezone(teh_tz)

#localize #timezone #pytz #astimezone #replace