python与javaScript之字符串操作

如果你接触过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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值