在 TypeScript 中,字符串(string
)的操作与 Python 高度相似,但由于 TypeScript 是 JavaScript 的超集,其字符串方法遵循 ECMAScript 标准。以下是 Python 字符串常见操作在 TypeScript 中的对等实现,包含代码示例和关键差异说明:
🧩 一、基础串接(拼接)
Python 示例:
ini
s1 = "Hello"
s2 = "World"
# 方式1:+ 拼接
combined1 = s1 + " " + s2 # "Hello World"
# 方式2:f-string(格式化)
name = "Alice"
age = 30
info = f"Name: {name}, Age: {age}" # "Name: Alice, Age: 30"
# 多行字符串
py_multi_str = """line1
line2"""
TypeScript 实现:
ini
// 多行字符串(用反引号`)
let tsMultiStr: string = `line1
line2`;
const s1: string = "Hello";
const s2: string = "World";
// 方式1:+ 拼接(同 Python)
const combined1: string = s1 + " " + s2; // "Hello World"
// 方式2:模板字符串(类似 f-string,用反引号 ` 和 ${})
const name: string = "Alice";
const age: number = 30;
const info: string = `Name: ${name}, Age: ${age}`; // "Name: Alice, Age: 30"
// 方式3:数组 join(适合批量拼接)
const parts: string[] = ["Type", "Script"];
const lang: string = parts.join("-"); // "Type-Script"
关键差异:
- TypeScript 模板字符串支持表达式 (如
${age + 1}
),Python f-string 同理。 - TypeScript 无
f-string
语法,但模板字符串功能完全覆盖。
✂️ 二、拆分(split
)
Python 示例:
ini
s = "apple,banana,orange"
# 按逗号拆分
fruits = s.split(",") # ["apple", "banana", "orange"]
# 限制拆分次数(maxsplit=1)
first_two = s.split(",", 1) # ["apple", "banana,orange"]
TypeScript 实现:
css
const s: string = "apple,banana,orange";
// 按逗号拆分(同 Python)
const fruits: string[] = s.split(","); // ["apple", "banana", "orange"]
// 限制拆分次数(第二个参数为 maxSplit)
const firstTwo: string[] = s.split(",", 1); // ["apple", "banana,orange"]
// 按正则拆分(如空格和逗号混合)
const mixed = "apple, banana; orange";
const items = mixed.split(/[,;\s]+/); // ["apple", "banana", "orange"]
关键差异:
- TypeScript 的
split
支持正则表达式 作为分隔符(Python 需通过re.split
),更灵活。 - 参数含义完全一致(第二个参数为最大拆分次数)。
🔍 三、前缀/后缀检查(startswith
/endswith
)
Python 示例:
ini
s = "https://example.com"
# 检查前缀
is_http = s.startswith("https://") # True
# 检查后缀
is_com = s.endswith(".com") # True
TypeScript 实现:
ini
const s: string = "https://example.com";
// 检查前缀(驼峰命名,同功能)
const isHttp: boolean = s.startsWith("https://"); // true
// 检查后缀(驼峰命名)
const isCom: boolean = s.endsWith(".com"); // true
// 支持指定起始/结束位置(Python 无此参数)
const substring = s.substring(0, 5); // "https"
const isHttps = substring.startsWith("http"); // true
关键差异:
- TypeScript 方法名使用驼峰式(
startsWith
/endsWith
),Python 用下划线(startswith
/endswith
)。 - TypeScript 额外支持起始/结束位置参数 (如
s.startsWith("ex", 8)
检查索引 8 开始的子串)。
🔄 四、替换(replace
)
Python 示例:
ini
s = "I like apples, apples are sweet"
# 替换所有匹配项(默认)
new_s = s.replace("apples", "oranges") # "I like oranges, oranges are sweet"
# 替换前 1 次
new_s_limit = s.replace("apples", "oranges", 1) # "I like oranges, apples are sweet"
TypeScript 实现:
typescript
const s: string = "I like apples, apples are sweet";
// 替换所有匹配项(默认行为)
const newS: string = s.replace("apples", "oranges"); // "I like oranges, oranges are sweet"
// 替换前 N 次(需用正则表达式 + g 标志)
const newSLimit: string = s.replace(/apples/g, "oranges"); // 同 Python 的 replace(..., 1) 需调整正则
// 注意:若需严格替换前 1 次,需手动控制(TS 无直接参数)
const manualReplace = s.replace("apples", "oranges", 1); // ❌ 报错(TS 不支持此参数)
// 正确方式:用正则匹配第一个出现的位置
const firstMatch = s.indexOf("apples");
const manualReplaced = firstMatch !== -1
? s.slice(0, firstMatch) + "oranges" + s.slice(firstMatch + "apples".length)
: s;
let s: string = "hello world";
// 替换所有匹配
console.log(s.replace(/world/g, "TypeScript")); // 输出:hello TypeScript
// 替换指定次数(TS 5.0+)
s = "a a a";
console.log(s.replaceAll("a", "b", 2)); // 输出:b b a
关键差异:
- TypeScript 的
replace
方法默认仅替换第一个匹配项(Python 默认替换所有)。 - 若需替换所有,TypeScript 需用正则表达式(如
/pattern/g
),Python 则通过count
参数控制。 - TypeScript 不支持直接指定替换次数(如
replace(old, new, count)
),需手动实现或用正则。
🔎 五、查找子串(find
/rfind
)
Python 示例:
ini
s = "hello world, hello python"
# 查找子串(返回首次出现的索引,不存在返回 -1)
idx = s.find("hello") # 0
# 查找最后一次出现的位置
last_idx = s.rfind("hello") # 13
TypeScript 实现:
typescript
const s: string = "hello world, hello python";
// 查找首次出现的索引(同 Python find)
const idx: number = s.indexOf("hello"); // 0
// 查找最后一次出现的索引(同 Python rfind)
const lastIdx: number = s.lastIndexOf("hello"); // 13
// 区分大小写的查找(Python 默认区分)
const caseSensitive = s.indexOf("Hello"); // -1(不存在)
// 不区分大小写的查找(需转换为统一大小写)
const caseInsensitive = s.toLowerCase().indexOf("HELLO".toLowerCase()); // 0
关键差异:
- TypeScript 用
indexOf
(首次)和lastIndexOf
(最后次)替代 Python 的find
和rfind
,功能完全一致。 - TypeScript 无直接的"不区分大小写"查找方法,需手动转换字符串大小写。
📝 六、大小写转换(lower
/upper
)
Python 示例:
ini
s = "Hello World"
# 转小写
lower_s = s.lower() # "hello world"
# 转大写
upper_s = s.upper() # "HELLO WORLD"
TypeScript 实现:
c
const s: string = "Hello World";
// 转小写(同 Python lower)
const lowerS: string = s.toLowerCase(); // "hello world"
// 转大写(同 Python upper)
const upperS: string = s.toUpperCase(); // "HELLO WORLD"
关键差异:
- 方法名完全对应(
toLowerCase
/toUpperCase
vslower
/upper
),功能无差异。
✨ 七、去除空白(strip
/lstrip
/rstrip
)
Python 示例:
ini
s = " \t Hello World \n "
# 去除两端空白
stripped = s.strip() # "Hello World"
# 去除左端空白
lstripped = s.lstrip() # "Hello World \n "
# 去除右端空白
rstriped = s.rstrip() # " \t Hello World"
TypeScript 实现:
typescript
const s: string = " \t Hello World \n ";
// 去除两端空白(同 Python strip)
const stripped: string = s.trim(); // "Hello World"
// 去除左端空白(同 Python lstrip)
const lstripped: string = s.trimStart(); // "Hello World \n "
// 去除右端空白(同 Python rstrip)
const rstripped: string = s.trimEnd(); // " \t Hello World"
// 自定义去除字符(Python 需传参数,TS 需手动实现)
const customStripped = s.replace(/^\s+|\s+$/g, ""); // 等效于 trim()
关键差异:
- TypeScript 用
trim
(两端)、trimStart
(左端)、trimEnd
(右端)替代 Python 的strip
、lstrip
、rstrip
。 - TypeScript 无直接去除指定字符的方法(如
strip("xy")
),需用正则表达式手动实现。
💎 八、完整操作示例
typescript
// 初始化字符串
let s: string = " TypeScript is fun ";
// 串接
const greeting: string = `Hello, ${s.trim()}`; // "Hello, TypeScript is fun"
// 拆分
const langs: string[] = "Python,Java,TS".split(","); // ["Python", "Java", "TS"]
// 前缀检查
const isTs: boolean = greeting.startsWith("Hello"); // true
// 替换
const newGreeting: string = greeting.replace("fun", "awesome"); // "Hello, TypeScript is awesome"
// 查找子串
const idx: number = newGreeting.indexOf("awesome"); // 19
// 大小写转换
const upper: string = newGreeting.toUpperCase(); // "HELLO, TYPESCRIPT IS AWESOME"
// 去除空白
const clean: string = newGreeting.trim(); // "Hello, TypeScript is awesome"
🆚 九、与 Python 的核心差异总结
操作 | Python 方法 | TypeScript 方法 | 关键差异 |
---|---|---|---|
串接 | + 、f-string |
+ 、模板字符串(${} ) |
语法相似,TS 模板字符串支持表达式 |
拆分 | split(sep, maxsplit) |
split(separator, limit) |
TS 支持正则分隔符 |
前缀检查 | startswith(prefix) |
startsWith(prefix) |
方法名驼峰式,TS 支持位置参数 |
后缀检查 | endswith(suffix) |
endsWith(suffix) |
同上 |
替换 | replace(old, new, count) |
replace(old, new) |
TS 默认替换首个,需正则实现全局替换 |
查找子串 | find(sub) 、rfind(sub) |
indexOf(sub) 、lastIndexOf(sub) |
方法名不同,功能一致 |
大小写转换 | lower() 、upper() |
toLowerCase() 、toUpperCase() |
方法名不同,功能一致 |
去除空白 | strip() 、lstrip() 、rstrip() |
trim() 、trimStart() 、trimEnd() |
方法名驼峰式,TS 无自定义字符去除 |
💡 总结建议
- TypeScript 字符串操作完全覆盖 Python 常用功能,仅需调整方法名(如驼峰式)。
- 注意 TS 对正则表达式的原生支持(如
split(/,/)
),比 Python 更灵活。 - 对于"替换前 N 次"或"自定义去除字符"等需求,TS 需结合正则或手动实现,但逻辑简单。
通过以上示例,Python 开发者可快速掌握 TypeScript 字符串操作,无缝迁移代码逻辑! 🚀