外观
字符串
字符串就是一系列字符。在Python中,用引号括起的都是字符串(单引号、双引号都行),如下所示:
python
"This is a string."
'This is also a string.'1
2
2
常见方法
title()
将每个单词的首字母转为大写。
python
name = "hello world"
# 输出:`Hello World`
print(name.title())1
2
3
4
2
3
4
upper()
将字符串全部转大写:
python
name = "Hello world"
# 输出 `HELLO WORLD`
print(name.upper())1
2
3
4
2
3
4
lower()
将字符串全部转小写:
python
name = "Hello world"
# 输出 `hello world`
print(name.lower())1
2
3
4
2
3
4
f-string(3.6+)
在字符串中使用变量。
python
first_name = "hello"
last_name = "world"
full_name = f"{first_name} {last_name}"
# 输出 `hello world`
print(full_name)1
2
3
4
5
6
2
3
4
5
6
format()(3.0 通用方案)
python
name = "hello"
age = 18
res = "姓名:{},年龄:{}".format(name, age)
# 输出 `姓名:hello,年龄:18`
print(res)1
2
3
4
5
6
2
3
4
5
6
符号处理
添加制表符
要在字符串中添加制表符,可使用字符组合 \t。
python
# 输出 `Python`
print("Python")1
2
2
python
输出 ` Python`
print("\tPython")1
2
2
添加换行符
要在字符串中添加换行符,可使用字符组合 \n:
python
print("Languages:\nPython\nC\nJavaScript")1
输出如下:
text
Languages:
Python
C
JavaScript1
2
3
4
2
3
4
删除左右空白
- 删除字符串右边的空白可以用
rstrip - 删除左边的空白可以用
lstrip() - 同时删除两边的空白可以用
strip()
python
favorite_language = 'python '
# 输出 `python`
favorite_language.rstrip()1
2
3
4
2
3
4