Replacing backslash '\' in python - python

When trying to replace '\' in python, the data changed and give me unknown letters.
i have tried string.replace, re.sub, regex_replace
a = '70\123456'
b = '70\123\456'
a = a.replace('\\','-')
b = b.replace('\\','-')
Expected Result:
a = '70-123456'
b = '70-123-456'
But The Actual Result is:
a = 70S456
b = 70SĮ
What is the problem and how to solve it?

That's because \123 and \456 are special characters(octal).
Try this:
a = r'70\123456'
b = r'70\123\456'
a = a.replace('\\','-')
b = b.replace('\\','-')
print(a)
print(b)

Related

Replace some string in python

I have two address like:
first_address = 'Красноярский край, г Красноярск, пр-кт им газеты Красноярский Рабочий, 152г, квартира (офис) /1'
second_address = 'Красноярский край, г Красноярск, пр-кт им.газеты "Красноярский рабочий", 152г'
And I want to replace all text before квартира (офис) /1
My code looks like:
c = first_address.split(',')
v = second_address.split(',')
b = c[:len(v)]
b = v
n = c[len(v)::]
f = ''.join(str(b)) + ''.join(str(n))
I get output:
['Красноярский край', ' г Красноярск', ' пр-кт им.газеты "Красноярский рабочий"', ' 152г'][' квартира (офис) /1']
How can I easily make this?
Looks like you want to take substrings from second_address until they run out, then use substrings from first_address. Here's a straightforward way to do it.
first_subs = first_address.split(',')
second_subs = second_address.split(',')
[(f if s is None else s)
for (f, s) in zip(first_subs,
second_subs + [None] * (len(first_subs) - len(second_subs)))]

Use a variable as index in Tkinter

How can I use a variable as index in ".get(startindex [,endindex])" expression, instead of numbers ?
I want something like this:
for i in range(1, n):
a = text.get("i.0", "i.end" )
b = text.get("i+1.0", "i+1.end" )
instead of:
a = text.get("1.0", "1.end" )
b = text.get("2.0", "2.end" )
a = text.get("3.0", "3.end" )
b = text.get("4.0", "4.end" ) etc...
In first sequence of code I get "bad text index "i.0" " error.
You have 3 way string format with python
text.get("%d.0"%(i + 1), "%.end"%(i)) # 1
text.get("{0}.0".format(i), "{0}.end".format(i) ) # 2
text.get(f"{i+1}.0", f"{i}.end") # 3
With only this information is hard to say what the purpose of this, but directly answering your question you can use string interpolation python.org such as .format method:
for i in range(1, n):
a = text.get("{0}.0".format(i), "{0}.end".format(i) )
b = text.get("{0}.0".format(i + 1), "{0}.end".format(i + 1))

Replace a substring in a string according to a list

According to tutorialspoint:
The method replace() returns a copy of the string in which the occurrences of old have been replaced with new. https://www.tutorialspoint.com/python/string_replace.htm
Therefore one can use:
>>> text = 'fhihihi'
>>> text.replace('hi', 'o')
'fooo'
With this idea, given a list [1,2,3], and a string 'fhihihi' is there a method to replace a substring hi with 1, 2, and 3 in order? For example, this theoretical solution would yield:
'f123'
You can create a format string out of your initial string:
>>> text = 'fhihihi'
>>> replacement = [1,2,3]
>>> text.replace('hi', '{}').format(*replacement)
'f123'
Use re.sub:
import re
counter = 0
def replacer(match):
global counter
counter += 1
return str(counter)
re.sub(r'hi', replacer, text)
This is going to be way faster than any alternative using str.replace
One solution with re.sub:
text = 'fhihihi'
lst = [1,2,3]
import re
print(re.sub(r'hi', lambda g, l=iter(lst): str(next(l)), text))
Prints:
f123
Other answers gave good solutions. If you want to re-invent the wheel, here is one way.
text = "fhihihi"
target = "hi"
l = len(target)
i = 0
c = 0
new_string_list = []
while i < len(text):
if text[i:i + l] == target:
new_string_list.append(str(c))
i += l
c += 1
continue
new_string_list.append(text[i])
i += 1
print("".join(new_string_list))
Used a list to prevent consecutive string creation.

Compare numbers in form: 12,3K , 1,84M in python

In need to compare numbers which look like: 12,3K , 1,84M, etc
eg:
a = 12,3K
b = 1,84M
if b > a :
print b
You need to use replace for it:
a = ("12,3K", "1,84M")
numbers = {"K": 1000, "M": 1000000}
result = []
for value in a:
if value:
i = value[-1]
value = float(value[:-1].replace(',', '.')) * numbers[i]
result.append(int(value))
print max(result)
You can add more numbers to dictionary and you will get more results.
I would recommend a function to convert a and b into the corresponding number like so (also I'd make a and b strings:
def convert(num):
return num.replace(',','').replace('K','000').replace('M','000000')
a = '12,3K'
b = '1,84M'
if convert(b) > convert(a) :
print b
If your values are strings, then the re module would make it easy to replace commas with '' and K or M with 3 or 6 zeroes. Then wrap in int() and compare. Where / how are you getting the values you're comparing?

Manipulation of list of strings in python

How A can be changed into B in python?
A = ['a.png', 'b.png', 'c.png', 'd.png', 'e.png']
B = 'a.png;b.png;c.png;d.png;e.png'
Simple, use str.join():
>>> A = ['a.png', 'b.png', 'c.png', 'd.png', 'e.png']
>>> B = ';'.join(A)
>>> print(B)
a.png;b.png;c.png;d.png;e.png
there's a function called join which might come to your rescue now:
try this:
b = ';'.join(a)`
in your case:
A = ['a.png', 'b.png', 'c.png', 'd.png', 'e.png']
B = ';'.join(A)
print b #this will return -> a.png;b.png;c.png;d.png;e.png

Categories

Resources