» Python快速入门 » 1. 基础篇 » 1.8 字符串

字符串

创建字符串

x = "lite"
x = 'rank'
x = str(12345) # convert number to string

x = '''This creates
a multiline string
example.'''

x = "*" * 5 # Repeat '*' five times, it produces "*****"

x = ",".join(["lite", "rank"]) # it produces "lite,rank"

获取子串

s = "literank.com"
print(s[4:8]) # rank, from character at index 4 to chracter at index 7 (the end position 8 is excluded)

可以使用负数作为起止索引。

s = "literank.com"
print(s[8:-1]) # .co

如果不提供起止索引,[:]切片操作会生成整个字符串。

s = "literank.com"
print(s[:]) # literank.com

拼接字符串

x, y = "lite", "rank"

print(x + y) # literank

x += y
print(x) # literank

# insert at specific index
x = "litrank"
c = 'e'
idx = 3
print(x[:idx]+c+x[idx:]) # literank

替代子串

x = "literank.org"
print(x.replace("org", "com")) # literank.com


# replace only 1 occurrence
x = "literank.org doesn't end with org"
print(x.replace("org", "com", 1)) # literank.com doesn't end with org

分割字符串

x = "lite,rank,.com"
print(x.split(',')) # ['lite', 'rank', '.com']

# Limit to 1 split "cut" only
print(x.split(',', 1)) # ['lite', 'rank,.com']

如果不给 split() 函数提供参数,默认按空格分割。

x = "l i t e r a n    k"
print(x.split()) # ['l', 'i', 't', 'e', 'r', 'a', 'n', 'k']

转换字符串

x = 'LiteRank'
print(x.lower()) # literank
print(x.upper()) # LITERANK

y = "rank"
print(y.capitialize()) # Rank

可以通过切片操作指定步长为 -1 来实现逆转字符串。

z = "hello world"
print(z[::-1]) # dlrow olleh

其他类型转化

x, y = '58', '58.12'

print(int(x)) # 58
print(float(y)) # 58.12
print([*y]) # ['5', '8', '.', '1', '2']

代码挑战

编辑代码使其输出 I'm LEARNING on literank.cn now.

Loading...
> 此处输出代码运行结果
上页
下页