python之字符串

要使用任何Python模块,都必须先导入:

有两种导入及使用方式:

一  import math  

     math.sqrt(5)

//导入模块名,以后使用时要在方法前面加上模块名

     

二 from math import*    

    log(25+5)

//这种方式导入时,如果函数与math模块中的某个函数同名,将被math模块中的同名函数覆盖。

>>> import math
>>> math.sqrt(5)
2.23606797749979
>>> from math import*
>>> log(25+5)
3.4011973816621555
>>> sqrt(4)*sqrt(10*10)
20.0

 log(25+5)为什么等于3.4呢?因为log默认以e为低。

>>> help(log)
Help on built-in function log in module math:

log(...)
    log(x[, base])
    
    Return the logarithm of x to the given base.
    If the base not specified, returns the natural logarithm (base e) of x.

在Python中,可使用下列3种主要方式来表示字符串字面量:

  1. 单引号,如 'http'
  2. 双引号,如 "http”
  3. 三引号,如 """http"""或者多行字符串: 

        """

        Me and my monkey

        have something to hide

        """ 

>>> 'http'
'http'
>>> "http"
'http'
>>> """http"""
'http'
>>> '''http'''
'http'
>>> ""'http'""
'http'
>>> "'"http"'""
SyntaxError: invalid syntax
>>> '''
ME and my monkey
have something to hide
'''
'
ME and my monkey
have something to hide
'

函数len(s)可以计算字符串的长度。

>>> len('http')
4
>>> len('')
0

可以将既有字符串”相加“来创建新的字符串,比如:

>>> 'hot' +"dog"
'hotdog'
>>> "Once"+' '+"upon"+'a Time'
'Once upona Time'

这种运算被称为拼接。

要将同一个字符串拼接很多次,可使用下面这种整洁的快捷方式:

>>> 10*'ha'
'hahahahahahahahahaha'
>>> 'hee'*3
'heeheehee'
>>> 3*'hee'+2*"!"
'heeheehee!!'

字符串拼接的结果为另一个字符串。