【Python 笔记】 join函数用法

在Python中,函数join()用来连接字符串。

>>>li = ['my','name','is','bob'] 
>>>' '.join(li) 
'my name is bob' 
 
>>>'_'.join(li) 
'my_name_is_bob' 
 
>>> s = ['my','name','is','bob'] 
>>> ' '.join(s) 
'my name is bob' 
 
>>> '..'.join(s) 
'my..name..is..bob' 
以上摘自王伟的博客: http://wangwei007.blog.51cto.com/68019/1100587


另外,在http://www.codewars.com上的Kata 中,有这样一道题:

Description:

Take an integer n (n >= 0) and a digit d (0 <= d <= 9) as an integer. Square all numbers k (0 <= k <= n) between 0 and n. Count the numbers of digits d used in the writing of all the k**2. Call nb_dig (or nbDig or ...) the function taking n and d as parameters and returning this count.

Examples:

n = 10, d = 1, the k*k are 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100
We are using the digit 1 in 1, 16, 81, 100. The total count is then 4.

nb_dig(25, 1):
the numbers of interest are
1, 4, 9, 10, 11, 12, 13, 14, 19, 21 which squared are 1, 16, 81, 100, 121, 144, 169, 196, 361, 441
so there are 11 digits `1` for the squares of numbers between 0 and 25.
Note that 121 has twice the digit 1.


Solution of  ‘zebulan’

def nb_dig(n, d):
    return ''.join(str(a ** 2) for a in xrange(n + 1)).count(str(d))


中,灵活使用了join和generator 的优势,仅用一行代码就搞定了我好几行代码的量,very clever~


你可能感兴趣的:(【Python,笔记】)