📌  相关文章
📜  Python - 在大小写转换之间添加 K

📅  最后修改于: 2022-05-13 01:54:21.233000             🧑  作者: Mango

Python - 在大小写转换之间添加 K

给定一个字符串,在发生大小写转换时添加 K。

方法 #1:使用循环 + isupper() + islower()

在这里,我们对每个元素进行迭代并检查每个元素是否下一个是不同的情况,如果是,则在结点中添加 K。

Python3
# Python3 code to demonstrate working of
# Add K between case shifts
# Using loop + isupper() + islower()
import re
  
# initializing string
test_str = 'GeeKSforGeEKs'
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing K
K = '^'
  
res = ""
for idx in range(0, len(test_str) - 1):
    # checking for case shift
    if test_str[idx].isupper() and test_str[idx + 1].islower() or test_str[idx].islower() and test_str[idx + 1].isupper():
        res = res + test_str[idx] + K
    else:
        res = res + test_str[idx]
res = res + test_str[-1]
  
# printing result
print("String after alteration : " + str(res))


Python3
# Python3 code to demonstrate working of
# Add K between case shifts
# Using loop + isupper() + islower()
  
# initializing string
test_str = 'GeeKSforGeEKs'
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing K
K = '^'
  
# join() to get result string
res = ''.join([test_str[idx] + K if (test_str[idx].isupper() and test_str[idx + 1].islower()) or
               (test_str[idx].islower() and test_str[idx + 1].isupper()) else test_str[idx] for idx in range(0, len(test_str) - 1)])
  
res += test_str[-1]
  
# printing result
print("String after alteration : " + str(res))


输出
The original string is : GeeKSforGeEKs
String after alteration : G^ee^KS^for^G^e^EK^s

方法#2:使用列表理解

解决这个问题的另一种方法,只是提供上述方法的简写。

蟒蛇3

# Python3 code to demonstrate working of
# Add K between case shifts
# Using loop + isupper() + islower()
  
# initializing string
test_str = 'GeeKSforGeEKs'
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing K
K = '^'
  
# join() to get result string
res = ''.join([test_str[idx] + K if (test_str[idx].isupper() and test_str[idx + 1].islower()) or
               (test_str[idx].islower() and test_str[idx + 1].isupper()) else test_str[idx] for idx in range(0, len(test_str) - 1)])
  
res += test_str[-1]
  
# printing result
print("String after alteration : " + str(res))
输出
The original string is : GeeKSforGeEKs
String after alteration : G^ee^KS^for^G^e^EK^s