[英]Not converting letters to uppercase and lowercase in python
I'm trying to make a program that will convert any text into a different form.我正在尝试制作一个将任何文本转换为不同形式的程序。 That means that a text such as 'hi there' becomes 'hI tHeRe'.
这意味着诸如“hi there”之类的文本变成了“hI tHere”。
list = []
word = input('Enter in a word or a sentence! ')
for num in range(len(word)):
list.clear()
list.append('i')
letter = word[num]
for x in range(len(list)):
if x % 2 == 0:
i = word.index(letter)
place = letter.lower()
word = word.replace(word[i], place)
if not x % 2 == 0:
i = word.index(letter)
place = letter.upper()
word = word.replace(word[i], place)
print(word)
However, when I run the code it just prints the same string as normal.但是,当我运行代码时,它只会打印与正常相同的字符串。
When using replace
, you have to assign the result to your variable:使用
replace
时,您必须将结果分配给您的变量:
word = word.replace(word[i], place)
However, replace
is actually not what you want here.但是,
replace
实际上不是您想要的。 replace
replaces all instances of a certain pattern with a new string. replace
用新字符串替换特定模式的所有实例。 In your current code, every instance of whatever letter word[i]
represents will be replaced with the result of .lower()
or .upper()
.在您当前的代码中,任何字母
word[i]
代表的每个实例都将替换为.lower()
或.upper()
的结果。
You also don't want to use the word list
, since doing so will shadow the Python built-in list
class.您也不想使用单词
list
,因为这样做会影响 Python 内置list
class。
If you want to keep most of your original logic, you can follow @khelwood's suggestion in the comments and end up with the following:如果您想保留大部分原始逻辑,可以在评论中遵循@khelwood 的建议并最终得到以下结果:
word = input('Enter in a word or a sentence! ')
wordList = list(word)
for i in range(len(word)):
if i % 2 == 0:
wordList[i] = word[i].lower()
else:
wordList[i] = word[i].upper()
print(''.join(wordList))
Here is one of my previous codes, you can change all the variable names to whatever you see fit.这是我以前的代码之一,您可以将所有变量名称更改为您认为合适的任何名称。
s = input('Enter in a word or string.')
ret = ""
i = True # capitalize
for char in s:
if i:
ret += char.upper()
else:
ret += char.lower()
if char != ' ':
i = not i
print(ret)
I hope it works for you.我希望这个对你有用。
Try this one liner -试试这个衬里 -
a = 'hi there'
''.join([i[1].lower() if i[0]%2==0 else i[1].upper() for i in enumerate(a)])
'hI ThErE'
If you care about each word starting from lowercase then this nested list comprehension works -如果您关心从小写开始的每个单词,那么这个嵌套列表理解有效 -
' '.join([''.join([j[1].lower() if j[0]%2==0 else j[1].upper() for j in enumerate(i)]) for i in a.split()])
'hI tHeRe'
The problem is with list.clear in the beginning of the for loop.问题在于 for 循环开头的 list.clear 。 Each iteration you clear the list so the second for iteration run on the first item only.
每次迭代都会清除列表,因此第二次迭代仅在第一项上运行。 Remove list.clear and it should scan the input word
删除 list.clear 它应该扫描输入的单词
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.