Checking two string in python? - python

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

Related

use .format() in a string in two steps

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

How to get the first 2 letters of a string in Python?

Let's say I have a string
str1 = "TN 81 NZ 0025"
two = first2(str1)
print(two) # -> TN
How do I get the first two letters of this string? I need the first2 function for this.
It is as simple as string[:2]. A function can be easily written to do it, if you need.
Even this, is as simple as
def first2(s):
return s[:2]
In general, you can get the characters of a string from i until j with string[i:j].
string[:2] is shorthand for string[0:2]. This works for lists as well.
Learn about Python's slice notation at the official tutorial
t = "your string"
Play with the first N characters of a string with
def firstN(s, n=2):
return s[:n]
which is by default equivalent to
t[:2]
Heres what the simple function would look like:
def firstTwo(string):
return string[:2]
In python strings are list of characters, but they are not explicitly list type, just list-like (i.e. it can be treated like a list). More formally, they're known as sequence (see http://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange):
>>> a = 'foo bar'
>>> isinstance(a, list)
False
>>> isinstance(a, str)
True
Since strings are sequence, you can use slicing to access parts of the list, denoted by list[start_index:end_index] see Explain Python's slice notation . For example:
>>> a = [1,2,3,4]
>>> a[0]
1 # first element, NOT a sequence.
>>> a[0:1]
[1] # a slice from first to second, a list, i.e. a sequence.
>>> a[0:2]
[1, 2]
>>> a[:2]
[1, 2]
>>> x = "foo bar"
>>> x[0:2]
'fo'
>>> x[:2]
'fo'
When undefined, the slice notation takes the starting position as the 0, and end position as len(sequence).
In the olden C days, it's an array of characters, the whole issue of dynamic vs static list sounds like legend now, see Python List vs. Array - when to use?
All previous examples will raise an exception in case your string is not long enough.
Another approach is to use
'yourstring'.ljust(100)[:100].strip().
This will give you first 100 chars.
You might get a shorter string in case your string last chars are spaces.
For completeness: Instead of using def you could give a name to a lambda function:
first2 = lambda s: s[:2]

Extract square-bracketed text from a string

Could someone please help me strip characters from a string to leave me with just the characters held within '[....]'?
For example:
a = newyork_74[mylocation]
b = # strip the frist characters until you reach the first bracket [
c = [mylocation]
Something like this:
>>> import re
>>> strs = "newyork_74[mylocation]"
>>> re.sub(r'(.*)?(\[)','\g<2>',strs)
'[mylocation]'
Assuming no nested structures, one way would be using itertools.dropwhile,
>>> from itertools import dropwhile
>>> b = ''.join(dropwhile(lambda c: c != '[', a))
>>> b
'[mylocation]'
Another would be to use regexs,
>>> import re
>>> pat = re.compile(r'\[.*\]')
>>> b = pat.search(a).group(0)
>>> b
'[mylocation]'

python convert unicode to string

I got my results from sqlite by python, it's like this kind of tuples: (u'PR:000017512',)
However, I wanna print it as 'PR:000017512'. At first, I tried to select the first one in tuple by using index [0]. But the print out results is still u'PR:000017512'. Then I used str() to convert and nothing changed. How can I print this without u''?
You're confusing the string representation with its value. When you print a unicode string the u doesn't get printed:
>>> foo=u'abc'
>>> foo
u'abc'
>>> print foo
abc
Update:
Since you're dealing with a tuple, you don't get off this easy: You have to print the members of the tuple:
>>> foo=(u'abc',)
>>> print foo
(u'abc',)
>>> # If the tuple really only has one member, you can just subscript it:
>>> print foo[0]
abc
>>> # Join is a more realistic approach when dealing with iterables:
>>> print '\n'.join(foo)
abc
Don't see the problem:
>>> x = (u'PR:000017512',)
>>> print x
(u'PR:000017512',)
>>> print x[0]
PR:000017512
>>>
You the string is in unicode format, but it still means PR:000017512
Check out the docs on String literals
http://docs.python.org/2/reference/lexical_analysis.html#string-literals
In [22]: unicode('foo').encode('ascii','replace')
Out[22]: 'foo'

how to get this string using python

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.

Categories