Python程序交换给定字符串的字符

Given a string, and we have to swap all characters using python program.

给定一个字符串,我们必须使用python程序交换所有字符。

In this article, we would learn how to return a string with swapped characters? This can be solved by either introducing a variable N or by just simply considering the length of the string itself.

在本文中,我们将学习如何返回带有交换字符的字符串? 这可以通过引入变量N或仅考虑字符串本身的长度来解决。

Question:

题:

If you are provided with a string, return a new string such that the first and the last characters have been exchanged. Also, you should consider the following cases:

如果提供了字符串,请返回一个新字符串,以使第一个和最后一个字符已交换。 另外,您应考虑以下情况:

Example:

例:

    swap_string ('love') = 'eovl'
    swap_string ('g') = 'g'
    swap_string ('ab') = 'ba'

Code:

码:

def swap_string(str):
    if len(str) <= 1:
        return str

    mid = str[1:len(str) - 1]
    return str[len(str) - 1] + mid + str[0]


print (swap_string('IncludeHelp'))
print (swap_string('Hello'))
print (swap_string('G'))
print (swap_string('I love my India!'))

Output

输出量

pncludeHelI
oellH
G
! love my IndiaI


翻译自: https://www.includehelp.com/python/program-to-swap-characters-of-a-given-string.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值