python如何實現Java substring() 方法?

Java substring() 方法java

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

語法數組

public String substring(int beginIndex)ide

code

public String substring(int beginIndex, int endIndex)索引

參數字符串

beginIndex -- 起始索引(包括), 索引從 0 開始。string

endIndex -- 結束索引(不包括)。it

返回值class

子字符串。

實例

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

相關文章
相關標籤/搜索