【笔记】Python | 02 | 变量和简单数据类型 | 2.3 字符串


字符串

字符串,就是一系列字符。Python中用括号引起的都是字符串,引号可以是单引号(''),也可以是双引号(“”)。

“This is a string.”
'This is a string.'

如果字符串中本来就有引号,可以将单引号与双引号混用。

'I told my friend, "Python is my favorite language!"'
"The language 'Python' is named after Monty Python, not the snake."
"One of Python's strengths is its diverse and supportive community."

修改大小写

修改字母大小写是最简单的操作之一。

name = "ada lovelace"
print(name.title())

将这个文件保存为name.py,运行后输出:

>>> Ada Lovelace

name.title()就是让Python对name执行方法title(),效果就是将单词的首字母变大写。

还有其他实用的方法:

name = "Ada Lovelace"

# 将所有字母转为大写
print(name.upper())

# 将所有字母转为小写
print(name.lower())

拼接字符串

有时候我们需要将字符串合并,例如将姓和名连起来。

first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
print(full_name)
print("Hello, " + full_name.title() + "!")

我们使用+合并字符串,得到结果:

>>> Hello, Ada Lovelace!

我们可以使用变量存储完整的消息,然后打印变量:

message = "Hello, " + full_name.title() + "!"
print(message)

制表符、换行符

我们使用换行或者空格来组织排列,使其更易读。

# \t添加制表符(4个空格)
print("\tPython")

# \n添加换行符
print("Languages:\nPython\nC\nJavaScript")

# 混合使用,\n\t让字符串换行并在开头添加空格
print("Languages:\n\tPython\n\tC\n\tJavaScript")

删除空白

对于人来说,'python'' python'没什么分别,但是对计算机而言,这是两个不同的字符串。

要确保字符串没有空白,可以这样:

# rstrip()去掉末尾空白(r可以记为right)

favorite_language = 'python '

print(favorite_language)
print(favorite_language.rstrip())
print(favorite_language)

还有其他的方法:

# lstrip()去掉开头的空白(l可以记为left)
# strip()去掉两端的空白

favorite_language = ' python '

print(favorite_language)
print(favorite_language.lstrip())
print(favorite_language.strip())