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 front


print (slice('Chocolate', 5))
print (slice('IncludeHelp', 7))
print (slice('Hello', 10)) #will print all characters

Output

输出量

Choco
Include
Hello


翻译自: https://www.includehelp.com/python/program-for-slicing-a-string.aspx

python字符串 切片

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值