许虎虎 开发者工具集

字符串实用程序

一组用 javascript 编写的字符串实用程序,可用于字符串操作以加快您的工作。




字符串实用程序

字符串实用程序是一些常用的工具和方法,用于对字符串进行操作和处理。常见的字符串操作包括查找、替换、分割、连接、裁剪、格式化等。下面是一些常见的字符串实用功能及其应用示例。

1. 大小写转换
转换为大写:
python

text = "hello world"
print(text.upper()) # 输出: "HELLO WORLD"
转换为小写:
python

text = "HELLO WORLD"
print(text.lower()) # 输出: "hello world"
首字母大写:
python

text = "hello world"
print(text.title()) # 输出: "Hello World"
首字母大写(仅第一个字母):
python

text = "hello world"
print(text.capitalize()) # 输出: "Hello world"
2. 字符串查找与替换
查找子字符串:
python

text = "hello world"
print(text.find("world")) # 输出: 6(返回子字符串的位置,如果没找到返回 -1)
替换子字符串:
python

text = "hello world"
print(text.replace("world", "Python")) # 输出: "hello Python"
检查字符串是否包含子字符串:
python

text = "hello world"
print("world" in text) # 输出: True
3. 字符串分割与连接
分割字符串:
python

text = "apple,banana,orange"
print(text.split(",")) # 输出: ['apple', 'banana', 'orange']
连接字符串:
python

words = ["apple", "banana", "orange"]
print(", ".join(words)) # 输出: "apple, banana, orange"
4. 去除空白字符
去除前后空白字符:
python

text = " hello world "
print(text.strip()) # 输出: "hello world"
去除前导空白字符:
python

text = " hello world "
print(text.lstrip()) # 输出: "hello world "
去除尾随空白字符:
python

text = " hello world "
print(text.rstrip()) # 输出: " hello world"
5. 字符串格式化
使用占位符(% 格式化):
python

name = "Alice"
age = 30
print("Name: %s, Age: %d" % (name, age)) # 输出: "Name: Alice, Age: 30"
使用 str.format() 方法:
python

name = "Alice"
age = 30
print("Name: {}, Age: {}".format(name, age)) # 输出: "Name: Alice, Age: 30"
使用 f-string(Python 3.6 及以上):
python

name = "Alice"
age = 30
print(f"Name: {name}, Age: {age}") # 输出: "Name: Alice, Age: 30"
6. 字符串的长度与索引
获取字符串的长度:
python

text = "hello world"
print(len(text)) # 输出: 11
获取字符串中的字符:
python

text = "hello world"
print(text[0]) # 输出: "h"
print(text[-1]) # 输出: "d"(从后面索引字符)
切片(获取子字符串):
python

text = "hello world"
print(text[0:5]) # 输出: "hello"(从位置 0 到位置 4)
7. 字符串是否符合某些条件
检查是否是数字:
python

text = "12345"
print(text.isdigit()) # 输出: True
检查是否是字母:
python

text = "hello"
print(text.isalpha()) # 输出: True
检查是否包含空格:
python

text = "hello world"
print(" " in text) # 输出: True
8. 字符串的转义字符
换行符:
python

text = "Hello\nWorld"
print(text)
# 输出:
# Hello
# World
制表符:
python

text = "Hello\tWorld"
print(text) # 输出: "Hello World"
反斜杠:
python

text = "Hello\\World"
print(text) # 输出: "Hello\World"
9. 字符串是否为空
检查字符串是否为空:
python

text = ""
print(text == "") # 输出: True

# 或者使用
print(not text) # 输出: True
10. Unicode 处理
编码字符串为字节:
python

text = "hello world"
encoded_text = text.encode("utf-8")
print(encoded_text) # 输出: b'hello world'
解码字节为字符串:
python

encoded_text = b'hello world'
decoded_text = encoded_text.decode("utf-8")
print(decoded_text) # 输出: "hello world"
11. 字符串的其他实用方法
字符串反转:
python

text = "hello world"
print(text[::-1]) # 输出: "dlrow olleh"
判断是否以特定字符开头:
python

text = "hello world"
print(text.startswith("hello")) # 输出: True
判断是否以特定字符结尾:
python

text = "hello world"
print(text.endswith("world")) # 输出: True