zoukankan      html  css  js  c++  java
  • python字符串操作(连接、比较、格式化等)(转)

    字符串连接
    方法一:
    Python代码

    1 >>> str1 = 'hello'
    2 >>> str2 = 'world'
    3 >>> str1_2 = str1 + ' ' + str2
    4 >>> str1_2
    5 'hello world'
    6 >>> print str1_2
    7 hello world
    8 >>>

    方法二:
    Python代码

    1 >>> str12 = '%s %s' % (str1, str2)
    2 >>> print str12
    3 hello world

    注意,下面方式是利用str1,str2初始化一个元组:
    Python代码

     1 >>> str_12 = str1, str2
     2 >>> str_12
     3 ('hello', 'world')
     4 #方括弧才是列表,元组是不可改变滴
     5 >>> str_1_2 = ['hello', 'world']
     6 >>> str_1_2
     7 ['hello', 'world']
     8 #另外顺便提一下,print末尾加逗号是把换行符替代成一个空格的意思。
     9 >>> print 'hello',
    10 ... 'world' 
    11 hello world

    ===============================================

    字符串比较
    Python代码

    1 >>> str = 'info' #我就犯这个错误,因为c中用str做变量很简洁
    2 >>> cmp(str, 'info')
    3 0
    4 
    5 >>> str == 'info' #返回值类型不同!!!尽管if语句中都能使用...
    6 True

    =================================================

    字符串注意事项:
    1. 不要像C语言那样使用str作为变量,因为str在python中是一个关键字,用于转换成字符串类型。
    Python代码

    1 >>> str = 'hello'
    2 >>> i = 5
    3 >>> str1 = str(i)
    4 Traceback (most recent call last):
    5   File "<stdin>", line 1, in <module>
    6 TypeError: 'str' object is not callable

    退出python后重新进入(只能退出重新运行,因为这里不是命令行而是python在对stdin进行解释执行(跟读入一个文件执行是一个道理,不过每次都要等待输入一行而已,行缓冲):
    Python代码

    1 >>> str1 = 'hello'
    2 >>> i = 5
    3 >>> str2 = str(i)
    4 >>> print str2
    5 5

    2. 要理解for x in yyy:中x不是关键词,而是一个我们定义的变量,python每次循环为这个变量赋值yyy中的1个(从最小到最大序号)。
    如:
    Python代码

    1 >>> str1 = ['str1', 'str2', 'str3']
    2 >>> for each in str1: #这里的each可以是任何变量名
    3 ...     print each,
    4 ...
    5 str1 str2 str3
    6 >>>
  • 相关阅读:
    2.HTML案例二 头条页面
    1.HTML入门
    33.1.网络编程入门
    32.原子性
    【转】风控中的特征评价指标(一)——IV和WOE
    【转】Python调用C语言动态链接库
    基于蒙特卡洛树搜索(MCTS)的多维可加性指标的异常根因定位
    正则表达式全集
    基于ray的分布式机器学习(二)
    基于ray的分布式机器学习(一)
  • 原文地址:https://www.cnblogs.com/xingmeng/p/3666542.html
Copyright © 2011-2022 走看看