# 将字符串切分为为列表 my_string = "how are you doing" a = my_string.split() # default argument is " " print(a) my_string = "one,two,three" a = my_string.split(",") print(a)
Hello World 11 HELLO WORLD hello world ['how', 'are', 'you', 'doing'] ['one', 'two', 'three'] True True 4 1 Hello Universe How are you doing
格式化
新样式使用 format() 方法,旧样式使用 % 操作符。
# 使用大括号做占位符 a = "Hello {0} and {1}".format("Bob", "Tom") print(a)
# 默认顺序时位置可以不写 a = "Hello {} and {}".format("Bob", "Tom") print(a)
a = "The integer value is {}".format(2) print(a)
# 一些数字的特殊格式化规则 a = "The float value is {0:.3f}".format(2.1234) print(a) a = "The float value is {0:e}".format(2.1234) print(a) a = "The binary value is {0:b}".format(2) print(a)
# old style formatting by using % operator # 旧的方式使用 % 操作符 print("Hello %s and %s" % ("Bob", "Tom")) # 多个参数时必需是元组 val = 3.14159265359 print("The decimal value is %d" % val) print("The float value is %f" % val) print("The float value is %.2f" % val)
Hello Bob and Tom Hello Bob and Tom The integer value is2 The float value is2.123 The float value is2.123400e+00 The binary value is10 Hello Bob and Tom The decimal value is10 The float value is10.123450 The float value is10.12
f-Strings
从 Python 3.6 起,可以直接在花括号内使用变量。
name = "Eric" age = 25 a = f"Hello, {name}. You are {age}." print(a) pi = 3.14159 a = f"Pi is {pi:.3f}" print(a) # f-Strings 在运行时计算,可以允许表达式 a = f"The value is {2*60}" print(a)
Hello, Eric. You are 25. Pi is3.142 The value is120