[英]Replacing Odd and Even-indexed characters in a string
How can I replace even and odd-indexed letters in my strings?如何替换字符串中的偶数和奇数索引字母? I'd like to replace odd-indexed characters with uppercased letters and even-indexed characters with lowercased ones.
我想用大写字母替换奇数索引字符,用小写字母替换偶数索引字符。
x=input("Enter String: ")
How can I modify the inputted string?如何修改输入的字符串?
This sounds a little like a "do my homework for me" post, but I'll help you out, as I need the training myself.这听起来有点像“帮我做作业”的帖子,但我会帮助你,因为我自己需要培训。
You can do this by breaking down the problem.你可以通过分解问题来做到这一点。 (As I am quite new with python syntax, I'm gonna assume that the user has already given an input to string x)
(因为我对 python 语法很陌生,我假设用户已经输入了字符串 x)
%2
).%2
) 检查数字是否为偶数。 This returns the remainder of a number when divided by 2. In the case of even numbers, that will be 0.%2 == 0
set letter to lower case, else set letter to upper case.%2 == 0
将字母设置为小写,否则将字母设置为大写。 Code:代码:
x = "seMi Long StRing WiTH COMPLetely RaNDOM CasINg"
result_string = ""
index = 0;
for c in x:
if(index%2 == 0):
result_string += c.lower()
else:
result_string += c.upper()
index+=1
print(result_string)
s=input()
l=[]
s=s.lower()
l=[i.upper() if s.index(i)%2==0 else i for i in s ]
print("".join(l))
def myfunc(string):
result=''
for x in range(len(string)):
if x%2==0:
result=result+string[x].upper()
else:
result=result+string[x].lower()
return result
The above is a function for the question you asked.以上是您提出的问题的功能。
A non-function for loop might be easier to grasp right now (like you I am very new to Python as well. So for me it was easier to understand the for loop before I got into functions. Look at my next post for the same.一个非函数的 for 循环现在可能更容易掌握(就像你一样,我对 Python 也很陌生。所以对我来说,在我进入函数之前更容易理解 for 循环。看我的下一篇文章也是一样的.
x = 'myname'
for item in range(len(x)):
if item%2==0:
print(x[item].upper())
else:
print(x[item].lower())
this is the for loop i was referring to.这是我所指的 for 循环。 but the thing with this line of code is that it is specific to the value you have assigned to the variable x where as the function i provided above can take any string value without us having to repeat the code each time.
但是这行代码的问题是它特定于您分配给变量 x 的值,因为我上面提供的函数可以采用任何字符串值,而我们不必每次都重复代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.