Manipulating strings in python
From raju
generate N random strings of maximum length L
from random import randint,choice from string import ascii_letters def rand_string(L): # return a string of L ascii letters [a..zA..Z] return ''.join((choice(ascii_letters) for _ in range(L))) def rand_vstring(Lmax): # return a string of variable length with maximum L characters return rand_string(randint(1,Lmax)) def rand_vstrings(N, Lmax): # return N strings with maximum L characters in each return [rand_vstring(Lmax) for _ in range(N)]
In [2]: rand_vstrings(8, 3) Out[2]: ['mwO', 'CbW', 'Ac', 'HK', 'VU', 'js', 'A', 'RsD'] In [3]: rand_vstrings(8, 4) Out[3]: ['g', 'UG', 'bETP', 'FB', 'RGg', 'Ehoh', 'HGMy', 'b'] In [4]: rand_vstrings(10, 4) Out[4]: ['XBC', 'L', 'aKV', 'FQe', 'gnh', 's', 'BzXV', 'Jxr', 'bcQN', 'IcUz']
using format
>>> a = '/foo/bar/{cob}' >>> a '/foo/bar/{cob}' >>> a.format(cob='20180916') '/foo/bar/20180916'
The original value is still unchanged.
>>> a '/foo/bar/{cob}'
To interpolate multiple things, all the values should be given in one go.
>>> b = '/foo/bar/{cob}/{version}' >>> b '/foo/bar/{cob}/{version}' >>> b.format(cob='20180916') Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'version' >>> b.format(cob='20180916', version='v5') '/foo/bar/20180916/v5'
As before, the original values remain unchanged.
>>> b '/foo/bar/{cob}/{version}'
Ref:- See also https://docs.python.org/3/library/string.html#format-examples -> "Accessing arguments by name"
string count
Q. How to count the number of occurrences of a given character in a string?
A.
>>> 'kamaraju'.count('a') 3 >>> 'kamaraju'.count('o') 0
character frequency without if statement
>>> def histogram(s): ... d = dict() ... for c in s: ... d[c] = d.get(c, 0) + 1 ... return d ... >>> histogram('brontosaurus') {'b': 1, 'r': 2, 'o': 2, 'n': 1, 't': 1, 's': 2, 'a': 1, 'u': 2}
last character(s) in string
>>> a = 'raju' >>> a[-1] 'u' >>> a[-1:] 'u' >>> a[-2:] 'ju' >>> type(a[-1]) <class 'str'> >>> type(a[-1:]) <class 'str'> >>> type(a[-2:]) <class 'str'>