简体   繁体   English

如何在一个句子中交替替换单词中的大写和小写字母? Python

[英]how to replace uppercase and lowercase letters in words alternately in a sentence? Python

i am new to python programming.我是 python 编程的新手。 I'm trying to learn about arrays and lists.我正在尝试了解 arrays 和列表。

I want to create a new program that can convert each word into uppercase and lowercase letters alternately in a sentence我想创建一个新程序,可以将句子中的每个单词交替转换为大写和小写字母

I've tried repeating several times, but I think I'm stuck here我试过重复几次,但我想我被困在这里

input_text = "hello my name is rahul and i'm from india"
result = ""
myArr = input_text.split(' ')

for idx in range(len(myArr)):
  if idx % 2 == 0 :
    result = result + myArr[idx].upper()
  else:
    result = result + myArr[idx].lower()

print(str(result))

With this code i can get for example:使用此代码,我可以获得例如:

input : "hello my name is rahul and i'm from india"
output : "HELLOmyNAMEisRAHULandI'MfromINDIA"

but what I am trying to get is actually is:但我想要得到的实际上是:

input : "hello my name is rahul and i'm from india"
output : "HELLO my NAME is RAHUL and I'M from INDIA"

I want to add a space to each word in the sentence.我想为句子中的每个单词添加一个空格。 But I don't know how.但我不知道怎么做。 please can someone advise where?请有人可以建议在哪里? Thanks in advance提前致谢

Any help would be appreciated.任何帮助,将不胜感激。

You've sort of got it -- the best way to do this is to add the capitalized/lowercased words to a list, then use .join() to turn the word list into a string with each word separated by a space:你已经明白了——最好的方法是将大写/小写的单词添加到列表中,然后使用.join()将单词列表转换为字符串,每个单词用空格分隔:

input_text = "hello my name is rahul and i'm from india"
result = ""
myArr = input_text.split(' ')
words = []
for idx in range(len(myArr)):
  if idx % 2 == 0 :
    words.append(myArr[idx].upper())
  else:
    words.append(myArr[idx].lower())

result = ' '.join(words)
print(str(result))

Contrary to what other answerers have suggested, using repeated concatenation is a bad idea for efficiency reasons .与其他回答者的建议相反, 出于效率原因,使用重复连接是一个坏主意

I have added space where you are appending to the list:我在您要附加到列表的位置添加了空间:

input_text = "hello my name is rahul and i'm from india"
result = ""
myArr = input_text.split(' ')

for idx in range(len(myArr)):
    if idx % 2 == 0 :
        result = result + myArr[idx].upper() + " "  # added a space
    else:
        result = result + myArr[idx].lower() + " "  # added a space

print(str(result))

This gives:这给出了:

HELLO my NAME is RAHUL and I'M from INDIA 

You can add all the values to a list and finally join them using the str.join method.您可以将所有值添加到列表中,最后使用str.join方法将它们连接起来。

input_text = "hello my name is rahul and i'm from india"
result = []
myArr = input_text.split(' ')

for idx in range(len(myArr)):
    if idx % 2 == 0:
        res = myArr[idx].upper()
    else:
        res = myArr[idx].lower()
    result.append(res)

print(" ".join(result))

Output: Output:

HELLO my NAME is RAHUL and I'M from INDIA

You can add a space to the result after adding each word, ie你可以在添加每个单词后在结果中添加一个空格,即

result = result + ' '

This will also add a space at the end of the string, which may not be desirable.这也会在字符串的末尾添加一个空格,这可能是不可取的。 You can remove it with the rstrip() function:您可以使用 rstrip() function 将其删除:

result = result.rstrip()

By the way, result is already a string, so you don't need to cast it to a string for the print statement.顺便说一句,result 已经是一个字符串,因此您不需要将其转换为 print 语句的字符串。

So, put it all together:所以,把它们放在一起:

input_text = "hello my name is rahul and i'm from india"
result = ""
myArr = input_text.split(' ')

for idx in range(len(myArr)):
  if idx % 2 == 0 :
    result = result + myArr[idx].upper()
  else:
    result = result + myArr[idx].lower()
  result = result + ' '

result = result.rstrip()    

print(result)

Using a list comprehension we can try:使用列表推导,我们可以尝试:

input_text = "hello my name is rahul and i'm from india"
words = input_text.split()
output = ' '.join([x.upper() if ind % 2 == 0 else x for ind, x in enumerate(words)])
print(output)  # HELLO my NAME is RAHUL and I'M from INDIA

In addition to the other answers, I provided another type of answers here using enumerate (see https://www.geeksforgeeks.org/enumerate-in-python/ ), which loop a list (or tuple) with its index:除了其他答案之外,我在这里使用enumerate提供了另一种类型的答案(请参阅https://www.geeksforgeeks.org/enumerate-in-python/ ),它使用其索引循环列表(或元组):

input_text = "hello my name is rahul and i'm from india"

result = []
for idx, word in enumerate(input_text.split()):
    result.append(word.upper() if idx % 2 == 0 else word.lower())
print(' '.join(result))

The answer also can be shorter like this using List Comprehension (see if/else in a list comprehension )答案也可以像这样使用 List Comprehension 更短(查看if/else in a list comprehension

input_text = "hello my name is rahul and i'm from india"

result = [word.upper() if idx % 2 == 0 else word.lower() for idx, word in enumerate(input_text.split())]
print(' '.join(result))

It would be helpful to know for your Python life:)了解您的 Python 寿命会很有帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM