官术网_书友最值得收藏!

Substrings or string slicing

Obtaining part of the string is a common exercise that we come across frequently in day-to-day string operations. Languages such as C or Java provide us with dedicated methods such as substr(st_index,end_index) or subString(st_index,end_index). To perform the substring operation in Python, there is no dedicated method, but we can instead use slicing. For example, if we wish to get the first four characters of our original my_str string, we can achieve this by using operations such as my_str[0:4], as shown in the following screenshot:

Again, the slice operation returns a new string and the changes are not applied to the original string. Furthermore, it is worth understanding here that the slicing happens over n-1 characters, where n is the upper limit, specified as the second parameter, which is four, in our case. Thus, the actual substring operation will be performed starting from index 0 and ending at index 3, thus returning the string Welc.

Let's take a look at some more examples of slicing:

  • To get the whole string from index 4, do the following:

  • To get the string from the start up to index 4, do the following:

  • To print the whole string with slicing, do the following:

  • To print the characters with a step of 2, do the following:

  • To print the reverse of the string, do the following:

  • To print a part of the string in reverse order, to the following:

主站蜘蛛池模板: 平陆县| 南部县| 宿迁市| 曲靖市| 西乌| 花垣县| 吉木乃县| 大悟县| 浮梁县| 溧水县| 天气| 江阴市| 长汀县| 同德县| 凌云县| 应用必备| 荔浦县| 浦县| 雷州市| 梅河口市| 陕西省| 宁陕县| 甘泉县| 新兴县| 衡东县| 丹阳市| 新巴尔虎左旗| 商河县| 肃北| 荆州市| 府谷县| 崇义县| 江西省| 宁晋县| 南宁市| 威信县| 共和县| 鄂尔多斯市| 南和县| 北海市| 息烽县|