python字符串 切片_用于切片字符串的Python程序
python字符串 切片
Given a string and number of characters (N), we have to slice and print the starting N characters from the given string using python program.
給定一個字符串和字符數( N ),我們必須使用python程序從給定的字符串中切片并打印開始的N個字符。
SLICING:
切片:
Slicing can be defined as selecting specific characters of a string. This can be performed easily by knowing the length of a string also if the length is not specified initially we can do it by selecting the number of characters that we require.
切片可以定義為選擇字符串的特定字符。 知道字符串的長度也可以很容易地做到這一點,如果最初沒有指定長度,我們可以通過選擇所需的字符數來實現。
Now let's understand slicing with a simple example,
現在讓我們用一個簡單的例子來了解切片
Question:
題:
We are provided with a string such that the first N characters are the front characters of the string. If the provided string length is less than N, the front is whatever we have got. Now your task is to create a new string such that it contains only the N characters from the front.
我們提供了一個字符串,使得前N個字符是字符串的開頭字符。 如果提供的字符串長度小于N ,則前面就是我們得到的。 現在,您的任務是創建一個新字符串,使其僅包含開頭的N個字符。
Example:
例:
slice('Javan', 3) = 'Jav'slice('Chocolava', 5) = 'Choco'slice('jio', 6) = 'jio'Solution:
解:
Here we have considered N as a number of the front end. Here as the length of the string is not mentioned initially so here we have done slicing by considering a specific number of characters.
在這里,我們將N視為前端數。 在這里,因為最初沒有提到字符串的長度,所以在這里我們通過考慮特定數目的字符來進行切片。
Code:
碼:
def slice(str, n):if len(str) < n:n = len(str)front = str[:n]return frontprint (slice('Chocolate', 5)) print (slice('IncludeHelp', 7)) print (slice('Hello', 10)) #will print all charactersOutput
輸出量
Choco Include Hello翻譯自: https://www.includehelp.com/python/program-for-slicing-a-string.aspx
python字符串 切片
總結
以上是生活随笔為你收集整理的python字符串 切片_用于切片字符串的Python程序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: a byte of python图书购买
- 下一篇: apple组织名称是什么_什么是Appl