Manipulation of list of strings in python - 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

Related

Replacing backslash '\' in 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)

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.

Printing variable label in function

How would I return a variable name in a function. E.g. If I have the function:
def mul(a,b):
return a*b
a = mul(1,2); a
b = mul(1,3); b
c = mul(1,4); c
This would return:
2
3
4
I would like it to return:
a = 2
b = 3
c = 4
How would I do this?
Unfortunately, you are unable to go "backwards" and print the name of a variable. This is explained in much further detail in this StackOverflow post.
What you could do is put the variable names in a dictionary.
dict = {"a":mul(1,2), "b":mul(1,3), "c":mul(1,4)}
From there you could loop through the keys and values and print them out.
for k, v in dict.items():
print(str(k) + " = " + str(v))
Alternatively, if you wanted your values ordered, you could put the values into a list of tuples and again loop through them in a for loop.
lst = [("a", mul(1,2)), ("b", mul(1,3)), ("c",mul(1,4))]
Here is how to do it with python-varname package:
from varname import varname
def mul(a, b):
var = varname()
return f"{var} = {a*b}"
a = mul(1,2)
b = mul(1,3)
c = mul(1,4)
print(a) # 'a = 2'
print(b) # 'b = 2'
print(c) # 'c = 2'
The package is hosted at https://github.com/pwwang/python-varname.
I am the author of the package. Let me know if you have any questions using it.

Python: print variable name and value easily

I want to use a function that can automatically print out the variable and the value. Like shown below:
num = 3
coolprint(num)
output:
num = 3
furthermore, it would be cool if it could also do something like this:
variable.a = 3
variable.b = 5
coolprint(vars(variable))
output:
vars(variable) = {'a': 3, 'b': 5}
Is there any function like this already out there? Or should I make my own? Thanks
From Python 3.8 there is a = for f-strings:
#!/usr/bin/env python3
python="rocks"
print(f"{python=}")
This would output
# python=rocks
This lambda-based solution works well enough for me, though perhaps not in every case. It is very simple and only consumes one line.
coolprint = lambda *w: [print(x,'=',eval(x)) for x in w]
Exmaple..
coolprint = lambda *w: [print(x,'=',eval(x)) for x in w]
a, *b, c = [1, 2, 3, 4, 5]
coolprint('a')
coolprint('b','c')
coolprint('a','b','c')
coolprint('c','b','b','a','b','c')
which produces..
a = 1
b = [2, 3, 4]
c = 5
a = 1
b = [2, 3, 4]
c = 5
a = 1
b = [2, 3, 4]
c = 5
c = 5
b = [2, 3, 4]
b = [2, 3, 4]
a = 1
b = [2, 3, 4]
c = 5
An official way to accomplish this task sadly doesn't exist even though it could be useful for many people. What I would suggest and I have used it sometimes in the past is the following(I am not sure if this is the best way to do it).
Basically what you can do is to create a custom object that mimics one Python's data type per time. Bellow you can find an example for an integer.
class CustomVariable(object):
def __init__(self, name, value):
self.name = name
self.value = value
def __str__(self):
return "{} = {}".format(self.name, self.value)
def __add__(self, val) :
return self.value + val
myVar = CustomVariable("myVar", 15)
print myVar
myVar = myVar + 5
print myVar
Output:
myVar = 15
myVar = 20
Check the special method named "___str____"
I'm just appending my custom print which accepts a list or a dict of expressions, adding the globals at the lateral case (excuse the PEP violation, I just love single-liners, especially with lambdas):
pp = lambda p: print(' | '.join([f"{x} = {eval(x)}" for x, v in {**p, **dict(**globals())}.items() if not x.startswith('_')])) if type(p)==dict else print(' | '.join([f"{x} = {eval(x)}" for x in p if not x.startswith('_')]))
# Some Variables:
z = {'a':100, 'b':200}
a = 1+15
# Usage with dict & all the variables in the script:
pp(dict(**locals()))
# Usage with list, for specific expressions:
pp(['a', "z['b']", """ {x:x+a for x in range(95, z['a'])} """])
Note that f'{x =}' won't work correctly, since the evaluation takes scope inside the function.
I have discovered the answer is No. There is no way to do this. However, your best bet is something like this:
from pprint import pprint
def crint(obj, name):
if isinstance(obj, dict):
print '\n' + name + ' = '
pprint(obj)
else:
print '\n' + name + ' = ' + str(obj)
that way you can just do:
crint(vars(table.content[0]), 'vars(table.content[0])')
or:
j = 3
crint(j, 'j')

Create a Python list filled with the same string over and over and a number that increases based on a variable.

I'm trying to create a list that is populated by a reoccurring string and a number that marks which one in a row it is. The number that marks how many strings there will be is gotten from an int variable.
So something like this:
b = 5
a = range(2, b + 1)
c = []
c.append('Adi_' + str(a))
I was hoping this would create a list like this:
c = ['Adi_2', 'Adi_3', 'Adi_4', 'Adi_5']
Instead I get a list like this
c = ['Adi_[2, 3, 4, 5]']
So when I try to print it in new rows
for x in c:
print"Welcome {0}".format(x)
The result of this is:
Welcome Adi_[2, 3, 4, 5]
The result I want is:
Welcome Adi_2
Welcome Adi_3
Welcome Adi_4
Welcome Adi_5
If anybody has Ideas I would appreciate it.
You almost got it:
for i in a:
c.append('Adi_' + str(i))
Your initial line was transforming the whole list a as a string.
Note that you could get rid of the loop with a list comprehension and some string formatting:
c = ['Adi_%s' % s for s in a]
or
c = ['Adi_{0}'.format(s) for s in a] #Python >= 2.6
Or as a list comprehension:
b = 5
a = range(2, b + 1)
c = ["Adi_" + str(i) for i in a]
Using list comprehensions:
b = 5
a = range(2, b + 1)
c = ['Adi_'+str(i) for i in a]
for x in c:
print"Welcome {0}".format(x)
Or all on one line:
>>> for s in ['Welcome Adi_%d' % i for i in range(2,6)]:
... print s
...
Welcome Adi_2
Welcome Adi_3
Welcome Adi_4
Welcome Adi_5

Categories

Resources