Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python中str的用法举例

作者:残情弑天   发布日期:2025-03-22   浏览:108

# 示例1:创建字符串
# 使用单引号或双引号创建字符串
s1 = 'Hello, world!'
s2 = "Python is fun!"
print(s1)  # 输出: Hello, world!
print(s2)  # 输出: Python is fun!

# 示例2:字符串拼接
# 使用 + 操作符拼接字符串
greeting = "Hello"
name = "Alice"
message = greeting + ", " + name + "!"
print(message)  # 输出: Hello, Alice!

# 示例3:字符串格式化
# 使用 f-string 进行格式化
age = 25
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)  # 输出: My name is Alice and I am 25 years old.

# 示例4:字符串方法
# 使用常用字符串方法如 upper(), lower(), strip(), replace() 等
text = "  hello world  "
print(text.upper())      # 输出: "  HELLO WORLD  "
print(text.lower())      # 输出: "  hello world  "
print(text.strip())      # 输出: "hello world"
print(text.replace("world", "Python"))  # 输出: "  hello Python  "

# 示例5:字符串索引和切片
# 使用索引和切片操作字符串
alphabet = "abcdefghijklmnopqrstuvwxyz"
print(alphabet[0])       # 输出: 'a'
print(alphabet[-1])      # 输出: 'z'
print(alphabet[0:5])     # 输出: 'abcde'
print(alphabet[-5:])     # 输出: 'vwxyz'

上一篇:python str to int

下一篇:python 除法取整

大家都在看

python时间格式

python ord和chr

python中的yield

python自定义异常

python list.pop

python的for i in range

npm config set python

python代码简单

python读取文件夹

python中turtle

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站