zoukankan      html  css  js  c++  java
  • Python——拼接字符串

    Python中可以对字符串进行拼接:

    1. 使用字符串拼接运算符: + 

    >>> "Hello" + "World"
    'HelloWorld'

    或:

    >>> str1 = "Hello"
    >>> str2 = "World"
    >>> str1 + str2
    'HelloWorld'

    又或:

    >>> str1 + "World"
    'HelloWorld'

    但是不允许str类型和整数类型的拼接,否则会报语法错:

    >>> "Hello" + 2018
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: must be str, not int

    示例:

    2. 字符串字面量常量同行并呈,Python解释器会将其合并为一个字面量常量:

    字面量常量间无空格:

    >>> "Hello""World"
    'HelloWorld'

    有空格:

    >>> "Hello" "World"
    'HelloWorld'

    并且不限于两个字面量,甚至是多个:

    >>> "Hello " "World, " "Python Newbies"
    'Hello World, Python Newbies'

    但是这种特性仅允许字符串的字面量常量之间,不允许出现字符串变量,如:

    >>> st1 = "Hello"
    >>> str2 = "World"
    >>> str1 str2
      File "<stdin>", line 1
        str1 str2
                ^
    SyntaxError: invalid syntax

    甚至是其中一个是变量,另一个是常量:

    >>> str1 = "Hello"
    >>> str1 "World"
      File "<stdin>", line 1
        str1 "World"
                   ^
    SyntaxError: invalid syntax
    >>> str1"World"
      File "<stdin>", line 1
        str1"World"
                  ^
    SyntaxError: invalid syntax

    本文完。

  • 相关阅读:
    开始熟悉一下数据结构了
    首个概率dp
    十六进制转化为八进制
    蓝桥之 剪格子
    蓝桥之 颠倒的价格
    还是闲的
    也是闲的
    闲的无聊,,,
    函数进阶
    函数基础
  • 原文地址:https://www.cnblogs.com/oddcat/p/9648822.html
Copyright © 2011-2022 走看看