I'm wondering what is the Python way to perform the following -
Given a set :
s = {'s1','s2','s3'}
I would like to perform something like :
s.addToAll('!')
to get
{'s1!','s2!','s3!'}
Thanks!
For an actual set:
>>> s = {'s1','s2','s3'}
>>> {x + '!' for x in s}
set(['s1!', 's2!', 's3!'])
That method is 2.7+, If you are using Python 2.6 you would have to do this instead:
>>> s = set(['s1','s2','s3'])
>>> set(x + '!' for x in s)
set(['s1!', 's2!', 's3!'])
You can try this:
>>> s = ['s1','s2','s3']
>>> list(i + '!' for i in s)
Related
How can I replace word with "word" in python?
I've already tried this:
str = "some_word"
str.replace("some_word", '"some_word"')
but this doesn't work
1) Don't use str as variable name as it is keyword in python.
d = 'ab'
print(d.replace('ab','ac'))
2) String are immutable in python so you have to re-assign it like:
d = d.replace('ab','ac')
print(d)
you should create a variable to receive the replaced value.
str = "some_word"
str = replace(old_chars, new_chars)
>>> strr = "some_word"
>>> strr = f'"{strr}"'
>>> print(strr)
"some_word"
This perfectly works:
a = "some_word"
print(a) # some_word
a = a.replace("some_word", '"some_word"')
print(a) # "some_word"
If you want to wrap the entire string in double quotes, and not only a part of it, you may use one of these approaches:
a = "some_word"
a1 = '"{}"'.format(a)
a2 = '"' + a + '"'
a3 = f'"{a}"'
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
let two strings
s='chayote'
d='aceihkjouty'
the characters in string s is present in d Is there any built-in python function to accomplish this ?
Thanks In advance
Using sets:
>>> set("chayote").issubset("aceihkjouty")
True
Or, equivalently:
>>> set("chayote") <= set("aceihkjouty")
True
I believe you are looking for all and a generator expression:
>>> s='chayote'
>>> d='aceihkjouty'
>>> all(x in d for x in s)
True
>>>
The code will return True if all characters in string s can be found in string d.
Also, if string s contains duplicate characters, it would be more efficient to make it a set using set:
>>> s='chayote'
>>> d='aceihkjouty'
>>> all(x in d for x in set(s))
True
>>>
Try this
for i in s:
if i in d:
print i
I have some Python code that pulls strings out of a text file:
[2.467188005806714e-05, 0.18664554919828535, 0.5026880460053854, ....]
Python code:
v = string[string.index('['):].split(',')
for elem in v:
new_list.append(float(elem))
This gives an error:
ValueError: could not convert string to float: [2.974717463860223e-06
Why can't [2.974717463860223e-06 be converted to a float?
You've still got the [ in front of your "float" which prevents parsing.
Why not use a proper module for that? For example:
>>> a = "[2.467188005806714e-05, 0.18664554919828535, 0.5026880460053854]"
>>> import json
>>> b = json.loads(a)
>>> b
[2.467188005806714e-05, 0.18664554919828535, 0.5026880460053854]
or
>>> import ast
>>> b = ast.literal_eval(a)
>>> b
[2.467188005806714e-05, 0.18664554919828535, 0.5026880460053854]
You may do the following to convert your string that you read from your file to a list of float
>>> instr="[2.467188005806714e-05, 0.18664554919828535, 0.5026880460053854]"
>>> [float(e) for e in instr.strip("[] \n").split(",")]
[2.467188005806714e-05, 0.18664554919828535, 0.5026880460053854]
The reason your code is failing is, you are not stripping of the '[' from the string.
You are capturing the first bracket, change string.index("[") to string.index("[") + 1
This will give you a list of floats without the need for extra imports etc.
s = '[2.467188005806714e-05, 0.18664554919828535, 0.5026880460053854]'
s = s[1:-1]
float_list = [float(n) for n in s.split(',')]
[2.467188005806714e-05, 0.18664554919828535, 0.5026880460053854]
v = string[string.index('[') + 1:].split(',')
index() return index of given character, so that '[' is included in sequence returned by [:].
i have a list like this :
a=[1000,200,30]
and i want to get a list like this :
['01000','00200','00030']
so what can i do ,
thanks
>>> a=[1000,200,30]
>>> [str(e).zfill(5) for e in a]
['01000', '00200', '00030']
str.zfill
str.format() is the preferred way to do this if you are using Python >=2.6
>>> a=[1000, 200, 30]
>>> map("{0:05}".format, a)
['01000', '00200', '00030']
You can do it like this:
a = [1000,200,30]
b = ["%05d" % (i) for i in a]
print b
The number tells the width and the leading zero says that you want leading zeros.
map(lambda x:str(x).zfill(5),a)
Look at formatting strings in Python.