字符串

字符串 #

定义字符串 #

Python 可以使用单引号或双引号定义字符串。

s = 'Hello World'
ds = "Hello World"

遍历字符 #

for c in s:
    print(c)

多行字符串 #

Python 使用 """ 标示多行文本。

text = """
    1, 2, 3 #{s}
    one, two, three
    "x, "y", "z"
"""

字符串转义 #

Python 可以使用 \ 进行字符串转义,也可以使用 r 表示直接原样输出。

print('c:\now')
print('c:\\now')
print(r'c:\now')

常用方法 #

截取字符串 #

左闭右开

print('Hello World'[6:9]) # Wor
print('Hello World'[:3])  # Hel

格式化字符串 #

print('{0} say {1}'.format('Marry', 'Hello'))
print('{name} say {msg}'.format(name='Marry', msg='Hello'))
# 四舍五入保留 2 位小数
print('{0:.2f}{1}'.format(1024.1024, 'GB'))

print('%s' % 97)
print('%c %c %c' % (65, 66, 67))
# 一共多少位.小数多少位
print('%10.2f' % 97.123)
沪ICP备17055033号-2