python如何实现Java substring() 方法?

Java substring() 方法

substring() 方法返回字符串的子字符串。

语法

public String substring(int beginIndex)

public String substring(int beginIndex, int endIndex)

参数

beginIndex -- 起始索引(包括), 索引从 0 开始。

endIndex -- 结束索引(不包括)。

返回值

子字符串。

实例

public class Test {

public static void main(String args[]) {

    String Str = new String("www.runoob.com");

    System.out.print("返回值 :" );

    System.out.println(Str.substring(4) );

    System.out.print("返回值 :" );

    System.out.println(Str.substring(4, 10) );

}

}

以上程序执行结果为:

返回值 :runoob.com

返回值 :runoob

Python中类似sunbstring应用方法

python中没有substring的定义,但是有更轻巧的实现,可以通过数组的slice来截取字符串

例如,在java中我们这样截取字符串:

String s = "Hello OutOfMemory.CN";

String small = s.subString(2,4);

而在python中,我们这样实现:

s = "Hello OutOfMemory.CN"

small = s[2:4]

python的用法更简单了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章