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的用法更簡單了。

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