如果你接触过python,也接触过javaScript,那么会发现它俩有相当多的相似之处,甚至有的时候连用法都差不多,如果会其中一个,在来学另一个,也就好学多了!
为了自己能加深学习备忘,写几篇它俩的相似之处,这篇记录下python与javaScript中的常用字符串操作。
索引取值
# python代码
a = 'abcdefg'
print(a[0]) # a
print(a[-1]) # g
print(a[10]) # IndexError: string index out of range
print(a['a']) # TypeError: string indices must be integers
// javaScript代码
let a = 'abcdefg';
console.log(a[0]); // a
console.log(a[-1]); // undefined
console.log(a[10]); // undefined
console.log(a['a']); // undefined
// php代码
$a = 'abcdefg';
echo $a[0]; // a
echo $a[-1]; // g
echo $a[10]; // 超过范围返回空
echo $a['a']; // Warning: Illegal string offset 'a'
总结
python:支持负数索引,如果索引超过范围报错:IndexError: string index out of range,如果索引不是数字报错:TypeError: string indices must be integers
JavaScript:负数索引,索引超过范围,索引不是数字一律返回undefined
php: 支持负数索引,如果索引超过范围返回空字符串,如果索引不是数字抛出警告:Warning: Illegal string offset 'a'
字符串分割
# python代码
a = 'a b c d'
print(a.split(' ')) # ['a', 'b', 'c', 'd']
print(a.split(' ', 1)) # ['a', 'b c d']
// JavaScript代码
let a = 'a b c d';
console.log(a.split(' ')); // ['a', 'b', 'c', 'd']
console.log(a.split(' ', 1)); // ['a']
总结
python:第二个参数为分割次数
JavaScript:第二个参数为限定返回数组的最大成员数
字符串中是否包含子字符串
- 相同
# python代码
a = 'abcdabcd'
print(a.find('a')) # 0
print(a.find('e')) # -1
print(a.find('a