代码之家  ›  专栏  ›  技术社区  ›  specialscope

Python中连接字符串和整数

  •  156
  • specialscope  · 技术社区  · 12 年前

    在Python中说你有

    s = "string"
    i = 0
    print s + i
    

    会给你错误,所以你写

    print s + str(i)
    

    以避免出错。

    我认为这是处理int和字符串串联的一种非常笨拙的方法。

    甚至Java也不需要显式转换为String来进行这种连接。 有没有更好的方法来进行这种串联,即在Python中不进行显式强制转换?

    9 回复  |  直到 2 年前
        1
  •  196
  •   user647772 user647772    12 年前

    现代字符串格式:

    "{} and {}".format("string", 1)
    
        2
  •  92
  •   Burhan Khalid    12 年前

    没有字符串格式:

    >> print 'Foo',0
    Foo 0
    
        3
  •  39
  •   Levon    12 年前

    字符串格式,使用新型 .format() 方法(具有默认值 .format() 提供):

     '{}{}'.format(s, i)
    

    或者年纪较大但“仍在身边”的人, % -格式设置:

     '%s%d' %(s, i)
    

    在上面的两个例子中 连接的两个项目之间的空间。如果需要空间,可以简单地将其添加到格式字符串中。

    这些提供了 大量 关于如何连接项目、项目之间的空间等的控制和灵活性。有关的详细信息 format specifications see this

        4
  •  21
  •   Peter Mortensen code4jhon    2 年前

    Python是一种有趣的语言,因为尽管通常有一种(或两种)“明显”的方法来完成任何给定的任务,但灵活性仍然存在。

    s = "string"
    i = 0
    
    print (s + repr(i))
    

    上面的代码片段是用Python3语法编写的,但后面的括号 打印 一直都是允许的(可选),直到版本3强制要求它们。

        5
  •  9
  •   Peter Mortensen code4jhon    2 年前

    在Python 3.6及更新版本中,您可以按照以下方式对其进行格式化:

    new_string = f'{s} {i}'
    print(new_string)
    

    或者只是:

    print(f'{s} {i}')
    
        6
  •  5
  •   Peter Mortensen code4jhon    2 年前

    format()方法可用于连接字符串和整数:

    print(s + "{}".format(i))
    
        7
  •  1
  •   Peter Mortensen code4jhon    2 年前

    您可以使用 f-string

    s = "string"
    i = 95
    print(f"{s}{i}")
    
        8
  •  0
  •   Peter Mortensen code4jhon    2 年前

    假设您希望在这样的情况下连接一个字符串和一个整数:

    for i in range(1, 11):
       string = "string" + i
    

    并且您得到了一个类型或串联错误。

    最好的办法是这样做:

    for i in range(1, 11):
       print("string", i)
    

    这将为您提供串联的结果,如字符串1、字符串2、字符串3等。

        9
  •  -1
  •   Peter Mortensen code4jhon    2 年前

    如果您只想打印,可以执行以下操作:

    print(s, i)