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
Having trouble writing a robust regular expression to grab information out of a string.
$ string1 = 'A_XYZ_THESE_WORDS'
$ string2 = 'A_ABC_THOSE_WORDS'
I would like a robust solution that pulls out from string1 or string2 respectfully 'THESE_WORDS' or 'THOSE_WORDS'.
Basically, I need something that removes everything before the first two underscores (_), but the text before them will vary.
$ get_text = re.search('(?<=A_)\w+(_)',string1)
$ print get_text.group()
$ 'XYZ_THESE_'
Based on your problem statement:
I need something that removes everything before the first two underscores
you don't necessarily need a regular expression:
>>> string1 = 'A_XYZ_THESE_WORDS'
>>> string1.split("_", 2)[2]
'THESE_WORDS'
The second argument to str.split is the maximum number of times to split. This will split on the first two '_'s, then take the third item (the rest of the string) from the resulting list.
This will throw an IndexError if there are fewer than two underscores in the string - this lets you know that the string is not in a format you expect, but if this behaviour is not desirable, consider:
>>> string1 = 'A_XYZ_THESE_WORDS'
>>> string1.split("_", 2)[-1]
'THESE_WORDS'
Which takes the last item in the list from str.split, rather than assuming that there will be three. Comparison:
>>> "JUST_ONE".split("_", 2)[2]
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
"JUST_ONE".split("_", 2)[2]
IndexError: list index out of range
>>> "JUST_ONE".split("_", 2)[-1]
'ONE'
The below regex will print the texts which was just after to the second underscore(_),
>>> import re
>>> string1 = 'A_XYZ_THESE_WORDS'
>>> string2 = 'A_ABC_THOSE_WORDS'
>>> m = re.search(r'^[^_]*_[^_]*_(.*)$', string1)
>>> m.group(1)
'THESE_WORDS'
>>> m = re.search(r'^[^_]*_[^_]*_(.*)$', string2)
>>> m.group(1)
'THOSE_WORDS'
In [21]: regex = re.compile(r'^([a-zA-Z]+_){2}(.*)$')
In [22]: m = regex.search(string1)
In [23]: m.groups()
Out[23]: ('XYZ_', 'THESE_WORDS')
In [24]: m = regex.search(string2)
In [25]: m.groups()
Out[25]: ('ABC_', 'THOSE_WORDS')
is there a quick way to place a string in the front of another string in python? if so how?
as an example let's say that string = 'pple'. How would I put the string_2 = 'a' at the start of string?
concatenate it:
string=char+string
>>> strg = 'pple'
>>> char = 'a'
>>> char + strg
'apple'
>>> strg = char + strg
>>> strg
'apple'
>>>
Here's a quick example:
string='a'+string
Lots of correct answers. You could also use "string interpolation" (or just "string formatting", when referring to str.format) if you are really looking to do some string manipulating (I only mention it because figuring out what the % is called can be frustrating):
>>> one_string = 'One string'
>>> two_string = 'two string'
>>> one_two = '%s, %s, red string, blue string' % (one_string, two_string)
>>> one_two
'One string, two string, red string, blue string'
I'll leave you to check it out if you like. See, for example, http://docs.python.org/library/stdtypes.html#string-formatting-operations
>>> word = '\u041a\u041e\u041b'
>>> print u'\u041a\u041e\u041b'
КОЛ
>>> print word
\u041a\u041e\u041b
How to transform string as a variable to a
readable kind (how print word)?
>>> print '\u041a\u041e\u041b'.decode('unicode-escape')
КОЛ
I've got a batch of strings that I need to cut down. They're basically a descriptor followed by codes. I only want to keep the descriptor.
'a descriptor dps 23 fd'
'another 23 fd'
'and another fd'
'and one without a code'
The codes above are dps, 23 and fd. They can come in any order, are unrelated to each other and might not exist at all (as in the last case).
The list of codes is fixed (or can be predicted, at least), so assuming a code is never used within a legitimate descriptor, how can I strip off everything after the first instance of a code.
I'm using Python.
The short answer, as #THC4K points out in a comment:
string.split(pattern, 1)[0]
where string is your original string, pattern is your "break" pattern, 1 indicates to split no more than 1 time, and [0] means take the first element returned by split.
In action:
>>> s = "a descriptor 23 fd"
>>> s.split("23", 1)[0]
'a descriptor '
>>> s.split("fdasfdsafdsa", 1)[0]
'a descriptor 23 fd'
This is a much shorter way of expressing what I had written earlier, which I will keep here anyway.
And if you need to remove multiple patterns, this is a great candidate for the reduce builtin:
>>> string = "a descriptor dps foo 23 bar fd quux"
>>> patterns = ["dps", "23", "fd"]
>>> reduce(lambda s, pat: s.split(pat, 1)[0], patterns, string)
'a descriptor '
>>> reduce(lambda s, pat: s.split(pat, 1)[0], patterns, "uiopuiopuiopuipouiop")
'uiopuiopuiopuipouiop'
This basically says: for each pat in patterns: take string and repeatedly apply string.split(pat, 1)[0] (like explained above), operating on the result of the previously returned value each time. As you can see, if none of the patterns are in the string, the original string is still returned.
The simplest answer is a list/string slice combined with a string.find:
>>> s = "a descriptor 23 fd"
>>> s[:s.find("fd")]
'a descriptor 23 '
>>> s[:s.find("23")]
'a descriptor '
>>> s[:s.find("gggfdf")] # <-- look out! last character got cut off
'a descriptor 23 f'
A better approach (to avoid cutting off the last character in a missing pattern when s.find returns -1) might be to wrap in a simple function:
>>> def cutoff(string, pattern):
... idx = string.find(pattern)
... return string[:idx if idx != -1 else len(string)]
...
>>> cutoff(s, "23")
'a descriptor '
>>> cutoff(s, "asdfdsafdsa")
'a descriptor 23 fd'
The [:s.find(x)] syntax means take the part of the string from index 0 until the right-hand side of the colon; and in this case, the RHS is the result of s.find, which returns the index of the string you passed.
You seem to be describing something like this:
def get_descriptor(text):
codes = ('12', 'dps', '23')
for c in codes:
try:
return text[:text.index(c)].rstrip()
except ValueError:
continue
raise ValueError("No descriptor found in `%s'" % (text))
E.g.,
>>> get_descriptor('a descriptor dps 23 fd')
'a descriptor'
codes = ('12', 'dps', '23')
def get_descriptor(text):
words = text.split()
for c in codes:
if c in words:
i = words.index(c)
return " ".join(words[:i])
raise ValueError("No code found in `%s'" % (text))
I'd probably use a regular expression to do this:
>>> import re
>>> descriptors = ('foo x', 'foo y', 'bar $', 'baz', 'bat')
>>> data = ['foo x 123', 'foo y 123', 'bar $123', 'baz 123', 'bat 123', 'nothing']
>>> p = re.compile("(" + "|".join(map(re.escape, descriptors)) + ")")
>>> for s in data:
m = re.match(p, s)
if m: print m.groups()[0]
foo x
foo y
bar $
baz
bat
It wasn't entirely clear to me whether you want what you're extracting to include text that precedes the descriptors, or if you expect each line of text to start with a descriptor; the above deals with the latter. For the former, just change the pattern slightly to make it capture all characters before the first occurrence of a descriptor:
>>> p = re.compile("(.*(" + "|".join(map(re.escape, descriptors)) + "))")
Here's an answer that works for all codes rather than forcing you to call the function for each code, and is a bit simpler than some of the answers above. It also works for all of your examples.
strings = ('a descriptor dps 23 fd', 'another 23 fd', 'and another fd',
'and one without a code')
codes = ('dps', '23', 'fd')
def strip(s):
try:
return s[:min(s.find(c) for c in codes if c in s)]
except ValueError:
return s
print map(strip, strings)
Output:
['a descriptor ', 'another ', 'and another ', 'and one without a code']
I believe this satisfies all of your criteria.
Edit: I realized quickly you could remove the try catch if you don't like expecting the exception:
def strip(s):
if not any(c in s for c in codes):
return s
return s[:min(s.find(c) for c in codes if c in s)]
def crop_string(string, pattern):
del_items = []
for indx, val in enumerate(pattern):
a = string.split(val, 1)
del_items.append(a[indx])
for del_item in del_items:
string = string.replace(del_item, "")
return string
example:
I want to crop the string and get only the array out of it..
strin = "crop the array [1,2,3,4,5]
pattern["[","]"]
usage:
a = crop_string(strin ,pattern )
print a
# --- Prints "[1,2,3,4,5]"