python 基础教程之2 字符串操作,变量

linux python基础教程 python 3.5

Posted by ivo on March 20, 2018

0x04 字符串操作

  • 字符串可以直接用+连接
    >>> 'good'+"good"
    'goodgood'
    
  • 数字在加引号以后也是按照字符串来处理
    >>> '2'+'2'
    '22'
    
    >>> 1+'2'+3+'4'
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: unsupported operand type(s) for +: 'int' and 'str'
    
  • 字符串在print 函数里面*就是打印几倍的关系
    >>> print('abc\n'*3)
    abc
    abc
    abc
    
    >>> print('abc'*3)
    abcabcabc
    
  • 单个字母不可以*也不可以+
    >>> print(a*3)
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    NameError: name 'a' is not defined
    
  • 在print函数里面数字的*就是*的关系来处理
    >>> print(4*3)
    12
    
    >>> 4*'222'
    '222222222222'
    
    >>> 4*'abc'
    'abcabcabcabc'
    
  • 不可以用浮点型来进行*操作
    >>> 4.0*'abc'
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: can't multiply sequence by non-int of type 'float'
    
  • 字符串与字符串*操作无效
    >>> '17'*'21'
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: can't multiply sequence by non-int of type 'str'
    
  • 在print函数里面+操作是无效的,不属于标准输入
    >>> print('abc'+3)
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: Can't convert 'int' object to str implicitly
    
    >>> print(a+3)
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    NameError: name 'a' is not defined
    
  • 在print函数里面字符串可以相加
    >>> print('abc'+'3')
    abc3
    

0x05 变量

  • 变量可以写在print里面
    >>> x=7
    >>> print(x)
    7
    >>> print(x+3)
    10
    >>> print(x)
    7
    
  • 字符串加双引号赋值变量
    >>> x = cde
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    NameError: name 'cde' is not defined
    
    >>> x = "cde"
    >>> print(x * 3)
    cdecdecde
    >>>
    
  • 同名变量被覆盖写入
    >>> x = 123
    >>> print(x)
    123
    >>> x = 'abc'
    >>> print(x)
    abc
    
  • 变量名称
  • python中的名字只能以包含 字母,数字,下划线,且不能以数字开头
  • python的变通是通过名称来占位的不用的可以用del删掉
    >>> foo = 'avc'
    >>> foo
    'avc'
    >>> del foo
    >>> foo
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    NameError: name 'foo' is not defined
    
  • pyhon支持 in-place操作如下
    >>> x = 1
    >>> x +=1
    >>> x
    2
    
    >>> x = 'abc'
    >>> x +='fgd'
    >>> x
    'abcfgd'