python怎么输入字母_如何在python中交换输入中的字母?

这不是小事。它可以通过字符串索引和切片来完成。但你也必须考虑到资本化的因素,并将其保留下来。在>>> s = "Hello"

>>> x = list(s)

>>> x

['H', 'e', 'l', 'l', 'o']

交换第一个与第三个和交换大小写

^{pr2}$

交换第二个和第四个>>> x[1], x[3] = x[3], x[1]

>>> x

['L', 'l', 'h', 'e', 'o']

把它变成一根绳子>>> ''.join(x)

'Llheo'

这并不适用于所有情况,但在这个特定的案例中,这正是您所要求的。在

编辑:使用函数进一步:def swap_letters(indexes, string):

"""

@indexes should be a list of 2-tuples of indexes to swap, e.g.:

[(0,2), (1,3)]

@string is the input string.

"""

letters = list(string)

for src, dst in indexes:

letter_src = letters[src]

letter_dst = letters[dst]

# Swap case on destination letter if src is upper

if letter_src.isupper():

letter_dst = letter_dst.upper()

letter_src = letter_src.lower()

letters[src], letters[dst] = letter_dst, letter_src

return ''.join(letters)

if __name__ == '__main__':

# This is the example from the OP

indexes = [(0,2), (1,3)]

word = 'Hello'

print swap_letters(indexes, word)

# And a proof of concept

indexes = [(0,-1), (6,4)]

word = 'ActiveSync'

print swap_letters(indexes, word)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值