Python字符串对齐和判断方法汇总
目录
- python ljust()、rjust()和center()方法
- 1. ljust()方法:左对齐
- 2. rjust()方法:右对齐
- 3. center()方法:居中对齐
- 4. 实际应用场景
- Python startswith()和endswith()方法
- 1. startswith()方法:判断字符串开头
- 2. endswith()方法:判断字符串结尾
- 3. 实际应用场景
- 总结
Python ljust()、rjust()和center()方法
1. ljust()方法:左对齐
ljust()方法用于将字符串左对齐,并使用指定字符(默认为空格)填充至指定长度。
# 基本语法:str.ljust(width[, fillchar])
# width:字符串的总长度
# fillchar:填充字符(可选,默认为空格)
# 示例1:使用默认空格填充
text = "Python"
result = text.ljust(10)
print(f"[{result}]")
# 输出:[Python ]
# 示例2:使用自定义字符填充
result = text.ljust(10, '*')
print(f"[{result}]")
# 输出:[Python****]
2. rjust()方法:右对齐
rjust()方法用于将字符串右对齐,并使用指定字符(默认为空格)填充至指定长度。
# 基本语法:str.rjust(width[, fillchar])
# 示例1:使用默认空格填充
text = "Python"
result = text.rjust(10)
print(f"[{result}]")
# 输出:[ Python]
# 示例2:使用自定义字符填充
result = text.rjust(10, '0')
print(f"[{result}]")
# 输出:[0000Python]
# 示例3:数字格式化
price = "99"
formatted_price = price.rjust(6, '0')
print(formatted_price)
# 输出:000099
3. center()方法:居中对齐
centerwww.devze.com()方法用于将字符串居中对齐,并使用指定字符(默认为空格)填充至指定长度。
# 基本语法:str.center(width[, fillchar])
# 示例1:使用默认空格填充
text = "Python"
result = text.center(10)
print(f"[{result}]")
# 输出:[ Python ]
# 示例2:使用自定义字符填充
result = text.center(10, '-')
print(f"[{result}]")
# 输出:[--Python--]
4. 实际应用场景
# 制作简单的文本表格
def print_table_row(item, price, width=20):
item_col = item.ljust(width)
price_col = str(price).rjust(8)
print(f"{item_col}{price_col}")
# 打印表头
print("商品清单".center(28, '='))
print_table_row(android"商品", "价格")
print("-" * 28)
# 打印数据
print_table_row("苹果", 5.5)
print_table_row("香蕉", 3.8)
print_table_row("橙子", 4.2)
# 输出:
# =========商品清单=========
# 商品 价格
# ----------------------------
# 苹果 5.5
# 香蕉 3.8
# 橙子 4.2
Python startswith()和endswith()方法
1. startswith()方法:判断字符串开头
startswith()方法用于检查字符串是否以指定的前缀开始。
# 基本语法:str.starphptswith(prefix[, start[, end]])
# prefix:要检查的前缀,可以是字符串或元组
# start:可选,开始检查的位置
# end:可选,结束检查的位置
# 示例1:基本用法
filename = "example.txt"
print(filename.startswith("ex")) # 输出:True
print(filename.startswith("py")) # 输出:False
# 示例编程客栈2:指定检查范围
text = "Hello, Python!"
print(text.startswith("Python", 7)) # 输出:True
# 示例3:多个前缀(使用元组)
filename = "document.pdf"
print(filename.startswith(("doc", "txt", "pdf"))) # 输出:True
2. endswith()方法:判断字符串结尾
endswith()方法用于检查字符串是否以指定的后缀结束。
# 基本语法:str.endswith(suffix[, start[, end]])
# 示例1:基本用法
filename = "example.txt"
print(filename.endswith(".txt")) # 输出:True
print(filename.endswith(".pdf")) # 输出:False
# 示例2:指定检查范围
text = "Hello, Python!"
print(text.endswith("Python", 0, 12)) # 输出:True
# 示例3:多个后缀(使用元组)
filename = "document.pdf"
print(filename.endswith((".doc", ".txt", ".pdf"))) # 输出:True
3. 实际应用场景
# 示例1:文件类型检查
def is_image_file(filename):
return filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif'))
# 测试文件类型
files = ['photo.jpg', 'document.pdf', 'image.png', 'script.py']
for file in files:
if is_image_file(file):
print(f"{file} 是图片文件")
else:
print(f"{file} 不是图片文件")
# 示例2:URL协议检查
def check_url_protocol(url):
if url.startswith('https://'):
return "安全连接"
elif url.startswith('http://'):
return "不安全连接"
else:
return "未知协议"
# 测试URL
urls = [
'https://www.example.com',
'http://www.example.com',
'ftp://www.example.com'
]
for url in urls:
print(f"{url}: {check_url_protocol(url)}")
总结
本教程详细介绍了Python中的字符串对齐方法(ljust、rjust和center)以及字符串判断方法(startswith和endswith):
字符串对齐方法:
- ljust():左对齐文本
- rjust():右对齐文本
- center():居中对齐文本这些方法在格式化输出、创建文本表格等场景中非常有用。
字符串判断方法:
- startswith():检查字符串开头
- endswith():检查字符串结尾这些方法在文件类型检查、URL验证TkGYQ等场景中经常使用。
掌握这些方法可以帮助你更好地处理文本数据,创建格式化输出,以及进行字符串匹配和验证。
加载中,请稍侯......
精彩评论