【Python基础】去除字符串空格、及f-string

Python语言是 大小写敏感 的。
Python的CSS选择器是大小写不敏感的。

1、注释符号:# 或

多行注释:可以使用三个单引号( )或者三个双引号(”””)来包围注释内容。
注意:这种多行字符串在Python中实际上被当作一个字符串(而不是注释),但是当它不被赋值时,一般作为多行注释使用。

单行注释符:# 单行代码
多行注释符:   多行代码   ,或"""多行代码"""

在Python中,字符串的单引号 ( ) 和双引号 (“)效果等同。主要取决于个人或团队的编码风格偏好。

2、去除空格:strip()

使用strip()方法不需要引入额外的包,由于它是内置在Python的字符串类型中。这个方法会移除字符串两端的空白字符,包括空格、制表符、换行符等。如下所示:

str = "   Hello, World!   "
trimmed = str.strip()  # 去除两端空格,输出: "Hello, World!"
trimmed = str.lstrip()  # 去除左侧空格,输出: "Hello, World!   "
trimmed = str.rstrip()  # 去除右侧空格,输出: "   Hello, World!"

3、f-string:f {表达式}

Python 3.6 引入了一种新的字符串格式化方法,称为格式化字符串字面值(一般称为 f-string)。f-string 以字母 f 或 F 开头,允许直接在字符串中用花括号{}嵌入表达式。

# 1. 包含变量
message = "Hello, world!"
print(f"{message}")

# 2. 包含表达式
a = 5
b = 10
print(f"{a} + {b} = {a + b}")

# 3. 调用函数
def greet(name):
    return f"Hello, {name}!"

print(greet("Kimi"))

# 4. 使用字典和列表
person = {"name": "Kimi", "age": 30}
print(f"{person[ name ]} is {person[ age ]} years old.")

items = ["apple", "banana", "cherry"]
print(f"Fruits: {len(items)} - {items}")

# 5. 格式化数字和文本
num = 12345.6789
print(f"Formatted number: {num:.2f}")

© 版权声明

相关文章

暂无评论

none
暂无评论...