【Python】如何优雅的处理字符串(一)

【Python】实用的处理字符串简单案例

1. 首字母大写

使用***str.capitalize()***方法可以将字符串的第一个字符转换为大写字母。

string = "hello world"
capitalized_string = string.capitalize()
print(capitalized_string)  
# 输出 "Hello world"

2. 将字符串按照分隔符分割成列表

使用***str.split()***方法可以将字符串按照指定的分隔符分割成一个列表。如果不指定分隔符,则默认使用空格。

string = "apple,orange,banana"
fruits_list = string.split(",")
print(fruits_list)  
# 输出 ["apple", "orange", "banana"]

3.将字符串拼接成一个新字符串

使用***str.join()***方法可以将一个字符串列表(或其他可迭代对象)的元素连接成一个新字符串。该方法的参数是一个可迭代对象,每个元素都是要连接的字符串。

fruits_list = ["apple", "orange", "banana"]
joined_string = ",".join(fruits_list)
print(joined_string)  
# 输出 "apple,orange,banana"

4.移除字符串中的空格

使用***str.strip()***方法可以移除字符串开头和结尾的空格。如果需要移除字符串中间的空格,则可以使用str.replace()方法。

string = "  hello world  "
stripped_string = string.strip()
print(stripped_string)  
# 输出 "hello world"

strip()补充:

strip()函数可以 用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列;
注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符

# 只要头尾包含有指定字符序列中的字符就删除
id_list = [1, 2, 3, 4]
sql = f"select * from user where 1 = 1 and id in ({str(id_list).strip('[]')})"
print(sql) 
# 输出 "select * from user where 1 = 1 and id in (1, 2, 3, 4)"

5.字符串格式化

方法1:使用***str.format()***方法可以将一个字符串中的占位符替换为指定的值。占位符用一对花括号{}表示,其中可以指定参数的名称、格式化方式等信息。

name = "Alice"
age = 25
formatted_string = "My name is {} and I'm {} years old.".format(name, age)
print(formatted_string)  
# 输出 "My name is Alice and I'm 25 years old."

方法2:Python中的f-string,其中的变量可以使用花括号{}括起来,并在前面加上字母"f"来表示这是一个格式化字符串。

name = "Alice"
age = 25
formatted_string = f"My name is {name} and I'm {age} years old."
print(formatted_string)  
# 输出 "My name is Alice and I'm 25 years old."

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yqyn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值