How do I get a substring of a string in Python?

前端 未结 13 1943
我寻月下人不归
我寻月下人不归 2020-11-22 00:32

Is there a way to substring a string in Python, to get a new string from the third character to the end of the string?

Maybe like myString[2:end]?

13条回答
  •  青春惊慌失措
    2020-11-22 01:13

    Using hardcoded indexes itself can be a mess.

    In order to avoid that, Python offers a built-in object slice().

    string = "my company has 1000$ on profit, but I lost 500$ gambling."
    

    If we want to know how many money I got left.

    Normal solution:

    final = int(string[15:19]) - int(string[43:46])
    print(final)
    >>>500
    

    Using slices:

    EARNINGS = slice(15, 19)
    LOSSES = slice(43, 46)
    final = int(string[EARNINGS]) - int(string[LOSSES])
    print(final)
    >>>500
    

    Using slice you gain readability.

提交回复
热议问题