I am going to define a function which takes a variable number of strings and examines each string and replaces / with -. and then return them back. (here is my logic problem - return what?)
def replace_all_slash(**many):
for i in many:
i = i.replace('/','-')
return many
is it correct? how can i recollect the strings as separate strings again?
example call:
allwords = replace_all_slash(word1,word2,word3)
but i need allwords to be separate strings as they were before calling the function. how to do this?
i hope i am clear to understand
You want to use *args (one star) not **args:
>>> def replace_all_slash(*words):
return [word.replace("/", "-") for word in words]
>>> word1 = "foo/"
>>> word2 = "bar"
>>> word3 = "ba/zz"
>>> replace_all_slash(word1, word2, word3)
['foo-', 'bar', 'ba-zz']
Then, to re-assign them into the same variables, use the assignment unpacking syntax:
>>> word1
'foo/'
>>> word2
'bar'
>>> word3
'ba/zz'
>>> word1, word2, word3 = replace_all_slash(word1, word2, word3)
>>> word1
'foo-'
>>> word2
'bar'
>>> word3
'ba-zz'
Solution one: create a new list and append that that:
def replace_all_slash(*many):
result = []
for i in many:
result.append(i.replace('/','-'))
return result
Solution two using a list comprehension:
def replace_all_slash(*many):
return [i.replace('/','-') for i in many]
You should rewrite your function:
def replace_all_slash(*args):
return [s.replace('/','-') for s in args]
and you can call it this way:
w1,w2,w3 = replace_all_slash("AA/","BB/", "CC/")
Disassembling the arguments in the calling code requires variables for each string.
word1,word2,word3 = replace_all_slash(word1,word2,word3)
Related
I aim to convert a proper noun for instance to have an upper case first letter after an input of the name has been made.
Using string.title() you achieve that:
>>> name = 'joe'
>>> name.title()
'Joe'
Use upper() method, like this:
mystr = "hello world"
mystr = mystr[0].upper() + mystr[1:]
.capitalize() and .title(), can be used, but both have issues:
>>> "onE".capitalize()
'One'
>>> "onE".title()
'One'
Both changes other letters of the string to smallcase.
Write your own:
>>> xzy = lambda x: x[0].upper() + x[1:]
>>> xzy('onE')
'OnE'
You can use https://pydash.readthedocs.io/en/latest/api.html#pydash.strings.capitalize.
Install pydash - pip install pydash
example:
from pydash import py_
greetings = "hello Abdullah"
py_.capitalize(greetings) # returns 'Hello abdullah'
py_.capitalize(greetings, strict = False) # returns 'Hello Abdullah'
I have a string in which I want to replace some variables, but in different steps, something like:
my_string = 'text_with_{var_1}_to_variables_{var_2}'
my_string.format(var_1='10')
### make process 1
my_string.format(var_2='22')
But when I try to replace the first variable I get an Error:
KeyError: 'var_2'
How can I accomplish this?
Edit:
I want to create a new list:
name = 'Luis'
ids = ['12344','553454','dadada']
def create_list(name,ids):
my_string = 'text_with_{var_1}_to_variables_{var_2}'.replace('{var_1}',name)
return [my_string.replace('{var_2}',_id) for _id in ids ]
this is the desired output:
['text_with_Luis_to_variables_12344',
'text_with_Luis_to_variables_553454',
'text_with_Luis_to_variables_dadada']
But using .format instead of .replace.
In simple words, you can not replace few arguments with format {var_1}, var_2 in string(not all) using format. Even though I am not sure why you want to only replace partial string, but there are few approaches that you may follow as a workaround:
Approach 1: Replacing the variable you want to replace at second step by {{}} instead of {}. For example: Replace {var_2} by {{var_2}}
>>> my_string = 'text_with_{var_1}_to_variables_{{var_2}}'
>>> my_string = my_string.format(var_1='VAR_1')
>>> my_string
'text_with_VAR_1_to_variables_{var_2}'
>>> my_string = my_string.format(var_2='VAR_2')
>>> my_string
'text_with_VAR_1_to_variables_VAR_2'
Approach 2: Replace once using format and another using %.
>>> my_string = 'text_with_{var_1}_to_variables_%(var_2)s'
# Replace first variable
>>> my_string = my_string.format(var_1='VAR_1')
>>> my_string
'text_with_VAR_1_to_variables_%(var_2)s'
# Replace second variable
>>> my_string = my_string % {'var_2': 'VAR_2'}
>>> my_string
'text_with_VAR_1_to_variables_VAR_2'
Approach 3: Adding the args to a dict and unpack it once required.
>>> my_string = 'text_with_{var_1}_to_variables_{var_2}'
>>> my_args = {}
# Assign value of `var_1`
>>> my_args['var_1'] = 'VAR_1'
# Assign value of `var_2`
>>> my_args['var_2'] = 'VAR_2'
>>> my_string.format(**my_args)
'text_with_VAR_1_to_variables_VAR_2'
Use the one which satisfies your requirement. :)
Do you have to use format? If not, can you just use string.replace? like
my_string = 'text_with_#var_1#_to_variables_#var2#'
my_string = my_string.replace("#var_1#", '10')
###
my_string = my_string.replace("#var2#", '22')
following seems to work now.
s = 'a {} {{}}'.format('b')
print(s) # prints a b {}
print(s.format('c')) # prints a b c
lets say I have 2 strings that are interchangeable, like a full word and it's abbreviation: 'max' and 'maximum'
I would like to set it so that they respond the same, for example if i have the following dictionary:
d = {'max':10,'a':5,'b':9}
d['maximum'] will return 10
is this even remotely possible?
note:
these two strings could be 'dog' and 'cat', they do not have to be related.
what I am asking is if I could do something like:
a = 'a' or 'b'
that way the two strings are interchangeable. I do understand that above is not correct syntax, I am just curious if anything like it is possible
You can do that using two dicts:
>>> key_dic = {'maximum':'max', 'minimum':'min'}
>>> d = {'max':10,'a':5,'b':9, 'min':-1}
def get_value(key):
return d[key_dic.get(key, key)]
...
>>> get_value('maximum')
10
>>> get_value('max')
10
>>> get_value('min')
-1
>>> get_value('minimum')
-1
You'll need to convert it into a function, class or something similar.
d_array = {'max':10,'a':5,'b':9}
def d(keyword):
if keyword == "maximum":
keyword = "max"
return d_array[keyword]
>>>print d("maximum")
10
I need to search a string for a list of several different matches, let's say I have this list:
['this', 'is', 'a', 'regex', 'test']
I want to see if any of those items is within a string, either using regex or any other method in Python.
I tried first just doing string in list, but that proved to be insufficient, so I tried concatenating the conditions in a regex like:
(this|is)(a|regex)(text)
But that tries to match several of the items as if they were concatenated.
You can use the built-in function any():
In [1]: strs="I am a string"
In [2]: lis=['this', 'is', 'a', 'regex', 'test']
In [3]: any(x in strs for x in lis)
Out[3]: True
This will return True for something like "thisisafoobar" as well.
But if you want to match the exact word, then try re.search() or str.split():
In [4]: import re
In [5]: any(re.search(r"\b{0}\b".format(x),strs) for x in lis)
Out[5]: True
In [6]: strs="foo bar"
In [7]: any(re.search(r"\b{0}\b".format(x),strs) for x in lis)
Out[7]: False
Using str.split():
In [12]: strs="I am a string"
In [13]: spl=strs.split() #use set(strs.split()) if the list returned is huge
In [14]: any(x in spl for x in lis)
Out[14]: True
In [15]: strs="Iamastring"
In [16]: spl=strs.split()
In [17]: any(x in spl for x in lis)
Out[17]: False
>>> l = ['this', 'is', 'a', 'regex', 'test']
>>> s = 'this is a test string'
>>> def check(elements, string):
... for element in elements:
... if element in string:
... return True
... return False
...
>>> check(l, s)
True
Apparently this function has better performance than any()
import time
def main():
# Making a huge list
l = ['this', 'is', 'a', 'regex', 'test'] * 10000
s = 'this is a test string'
def check(elements, string):
for element in elements:
if element in string:
return True
return False
def test_a(elements, string):
"""Testing check()"""
start = time.time()
check(elements, string)
end = time.time()
return end - start
def test_b(elements, string):
"""Testing any()"""
start = time.time()
any(element in string for element in elements)
end = time.time()
return end - start
print 'Using check(): %s' % test_a(l, s)
print 'Using any(): %s' % test_b(l, s)
if __name__ == '__main__':
main()
Results:
pearl:~ pato$ python test.py
Using check(): 3.09944152832e-06
Using any(): 5.96046447754e-06
pearl:~ pato$ python test.py
Using check(): 1.90734863281e-06
Using any(): 7.15255737305e-06
pearl:~ pato$ python test.py
Using check(): 2.86102294922e-06
Using any(): 6.91413879395e-06
But if you combine any() with map() in something like any(map(lambda element: element in string, elements)), these are the results:
pearl:~ pato$ python test.py
Using check(): 3.09944152832e-06
Using any(): 0.00903916358948
pearl:~ pato$ python test.py
Using check(): 2.86102294922e-06
Using any(): 0.00799989700317
pearl:~ pato$ python test.py
Using check(): 3.09944152832e-06
Using any(): 0.00829982757568
You could do:
if any(test in your_string for test in tests):
...
I've been using Perl for some time and have gotten used to the syntax:
return "$var1$var2";
for easily returning a concatenation of two strings in one step. Is there a way to do something similar in Python? I'd love to avoid doing it in two steps, if possible.
Simple:
>>> "a" + "b"
'ab'
>>> "%s%s" % ("a", "b")
'ab'
>>> "{a}{b}".format(a="a", b="b")
'ab'
>>> "{}{}".format("a", "b")
'ab'
>>> "{0}{1}".format("a", "b")
'ab'
>>> "a" "b"
'ab'
>>> "".join(("a", "b"))
'ab'
I don't see how addition is two steps.
return var1 + var2
just use +.
def f():
a = 'aaa'
b = 'bbb'
return a + b