【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."