zoukankan      html  css  js  c++  java
  • 字符串连接的5种方法

    1. 加号

    第一种,有编程经验的人,估计都知道很多语言里面是用加号连接两个字符串,Python里面也是如此直接用 “+” 来连接两个字符串;

    >>> print("hello "+"world")

    hello world

    2. 逗号

    第二种比较特殊,使用逗号连接两个字符串,如果两个字符串用“逗号”隔开,那么这两个字符串将被连接,但是,字符串之间会多出一个空格;

    >>> print('hello','world')

    hello world

    3. 直接连接

    第三种也是 ,python 独有的,只要把两个字符串放在一起,中间有空白或者没有空白,两个字符串将自动连接为一个字符串;

    >>> print('hello''world')

    helloworld

    或者

    >>> print('hello'   'world')

    helloworld

    4. 格式化

    第四种功能比较强大,借鉴了C语言中 printf 函数的功能,如果你有C语言基础,看下文档就知道了。这种方式用符号“%”连接一个字符串和一组变量,字符串中的特殊标记会被自动用右边变量组中的变量替换:

    >>> print('%s %s' % ('hello','world'))

    hello world

    5. join

    就属于技巧了,利用字符串的函数 join 。这个函数接受一个列表,然后用字符串依次连接列表中每一个元素:

    >>> str_list = ['hello','world']

    >>> a = ''

    >>> print(a.join(str_list))

    helloworld

  • 相关阅读:
    ZINTERSTORE — Redis 命令参考
    Wombat vim colorscheme – customized Chronosbox
    我的vim colorscheme 白色之夜 博客园
    Python list of class attributes Python
    vim配色方案colorscheme设置
    colorscheme install
    Python类中的私有成员(私有函数,私有变量)
    Pebble Overview
    用python 发送邮件
    Python发送带附件的Email
  • 原文地址:https://www.cnblogs.com/-simon/p/5887614.html
Copyright © 2011-2022 走看看