I'm trying to make it so that my text alternates between upper and lower case like the question ask. It seems to skip 3 in the indexing and I can't figure out why.
sentence = input("Write a sentence")
newList = []
for i in range(len(sentence)):
if sentence[i] != " ":
newList.append(sentence[i])
listJoint = "".join(newList)
newList2 = []
for i in range(len(listJoint)):
if (listJoint.index(listJoint[i]) % 2) == 0:
print(listJoint.index(listJoint[i]))
newList2.append(listJoint[i].upper())
elif (listJoint.index(listJoint[i]) % 2) != 0:
print(listJoint.index(listJoint[i]))
newList2.append(listJoint[i].lower())
print(newList2)
#newListJoint = "".join(newList2)
#print(newListJoint[::-1])
Thanks in advance
List index doesn't go 0 1 2 3 4
The function .index() finds the first occurrence of that letter. 'L' occurs at index 2 and 3 so it would return 2 for both L's.
Iterate through each character of the string and alternate upper/lower methods.
sentence = "Hello"
alternated_sentence = ''
for i, char in enumerate(sentence):
if i % 2:
alternated_sentence += char.upper()
else:
alternated_sentence += char.lower()
print(alternated_sentence)
#hElLo
sentence = input("Write a sentence:")
# Remove spaces (as per your question)
sentence = sentence.replace(' ', '')
# Reverse the string order (as per your question)
sentence = sentence[::-1]
result = []
for i in range(len(sentence)):
if(i%2==1):
result.append(sentence[i].lower())
else:
result.append(sentence[i].upper())
print(''.join(result))
Here's the solution. The above code would give output as follows:
Write a sentence: Hello world
DlRoWoLlEh
I never realised index method referenced the first instance of the character. This works:
sentence = input("Write a sentence")
newList = []
for i in range(len(sentence)):
if sentence[i] != " ":
newList.append(sentence[i])
listJoint = "".join(newList)
newList2 = []
for i, value in enumerate(newList):
if i % 2 == 0:
newList2.append(listJoint[i].upper())
elif i % 2 !=0:
newList2.append(listJoint[i].lower())
newListJoint = "".join(newList2)
print(newListJoint[::-1])
Related
I have two input strings. In the first one - words with spaces. In the second - the word with same count of symbols without spaces. The task is to split the second string into array by spaces in the first one.
I tried to make it with cycles but there is problem of index out of range and i can't find another solution.
a = str(input())
b = str(input())
b_word = str()
b_array = list()
for i in range(len(a)):
if a[i] != " ":
b_word += b[i]
else:
b_array += b_word
b_word = str()
print(b_array)
Input:
>>head eat
>>aaabbbb
Output:
Traceback (most recent call last):
File "main.py", line 29, in <module>
b_word += b[i]
IndexError: string index out of range
Expected output:
>> ["aaab", "bbb"]
Thanks in advance!
Consider a solution based on iterator and itertools.islice method:
import itertools
def split_by_space(s1, s2):
chunks = s1.split()
it = iter(s2) # second string as iterator
return [''.join(itertools.islice(it, len(c))) for c in chunks]
print(split_by_space('head eat or', 'aaaabbbcc')) # ['aaaa', 'bbb', 'cc']
a = input() # you don't need to wrap these in str() since in python3 input always returns a string
b = input()
output = list()
for i in a.split(' '): # split input a by spaces
output.append(b[:len(i)]) # split input b
b = b[len(i):] # update b
print(output)
Output:
['aaab', 'bbb']
You can do something like this:
a = input()
b = input()
splitted_b = []
idx = 0
for word in a.split():
w_len = len(word)
splitted_b.append(b[idx:idx+w_len])
idx += w_len
print(splitted_b)
The idea is taking consecutive sub-strings from b of the length of each word on a.
Instead of using indices, you can iterate over each character of a. If the character is not a space, add the next character of b to your b_word. If it is a space, add b_word to the b_array
b_iter = iter(b) # Create an iterator from b so we can get the next character when needed
b_word = []
b_array = []
for char in a:
# If char is a space, and b_word isn't empty, append it to the result
if char == " " and b_word:
b_array.append("".join(b_word))
b_word = []
else:
b_word.append(next(b_iter)) # Append the next character from b to b_word
if b_word: # If anything left over in b_word, append it to the result
b_array.append("".join(b_word))
Which gives b_array = ['aaab', 'bbb']
Note that I changed b_word to a list that I .append to every time I add a character. This prevents the entire string from being recreated every time you append a character.
Then join all the characters using "".join(b_word) before appending it to b_array.
So to accomodate for any number of spaces in the input it gets a bit more complex as the indexes of the letters will change with each space that is added. So to gather all of the spaces in the string I created this loop which will account of the multiple spaces and alter the index with each new space in the initial word.
indexs = []
new = ''
for i in range(len(a)):
if len(indexs) > 0:
if a[i] == ' ':
indexs.append(i-len(indexs))
else:
if a[i] == ' ':
indexs.append(i)
Then we simple concatenate them together to create a new string that includes spaces at the predetermined indexes.
for i in range(len(b)):
if i in indexs:
print(i)
new += " "
new += b[i]
else:
new += b[i]
print(new)
Hope this helps.
Code
sone = input()
stwo = 'zzzzzxxxyyyyy'
nwz = []
wrd = ''
cnt = 0
idx = 0
spc = sone.split(' ') #split by whitespace
a = [len(i) for i in spc] #list word lengths w/out ws
for i in stwo:
if cnt == a[idx]: #if current iter eq. word length w/out ws
nwz.append(wrd) #append the word
wrd = '' #clear old word
wrd = wrd + i #start new word
idx = idx + 1
cnt = 0
else:
wrd = wrd + i #building word
cnt = cnt + 1
nwz.append(wrd) #append remaining word
print(nwz)
Result
>'split and match'
['zzzzz', 'xxx', 'yyyyy']
My goal is to write a function which change every even letter into upper letter and odd to lower (space also count as a one element).
This is my code
def to_weird_case(s):
for i in s:
if len(i) % 2 == 0:
s[i] = i.upper() + s(i+1)
else:
s[i] = i.lower() + s(i+2)
return i
I think it should be quite correct, but it gives me error.
line 7, in to_weird_case
s[i] = i.lower() + s(str(i)+2)
TypeError: must be str, not int
EDIT:
I have a sugesstion but I don't know how to make it. I try it for myself and back here.
This needs to definitly explicietly state that the zero indexing uppercase is for each word.
Do you know guys how to make it?
So we can analyze your code and just explain what you typed:
def to_weird_case(s):
for i in s: # s is your string, and i is the actual character
if len(i) % 2 == 0: # if your length of the character can be divided by 2. Hmm this is weird
s[i] = i.upper() + s(i+1) # s[i] change a character in the string but you should provide an index (i) so an integer and not a character. But this is not supported in Python.
else:
s[i] = i.lower() + s(i+2)
return i # This will exit after first iteraction, so to_weird_case("this") will return "t".
So what you need to is first create a output string and fill that. And when iteration over s, you want the index of the char and the char value itself.
def to_weird_case(s):
output = ""
for i, myChar in enumerate(s):
if i % 2 == 0:
output += myChar.upper()
else:
output += myChar.lower()
return output
my_sentence = "abcdef"
print(to_weird_case(my_sentence))
And when you want to ignore spaces, you need to keep track of actual characters (excluding spaces)
def to_weird_case(s):
output = ""
count = 0
for myChar in s:
if myChar.isspace():
output += myChar
else:
if count % 2 == 0:
output += myChar.upper()
else:
output += myChar.lower()
count += 1
return output
my_sentence = "abc def"
print(to_weird_case(my_sentence))
Test this yourself
def to_weird_case(s):
for i in s:
print (i)
After doing this you will find that i gives you characters.
if len(i) % 2 == 0:
This line is incorrect as you are trying to find the length of a single character. len(s) would be much better.
So the code will be like
def to_weird_case(s):
s2 = "" #We create another string as strings are immutable in python
for i in range(len(s)):
if i % 2 == 0:
s2 = s2 + s[i].upper()
else:
s2 = s2 + s[i].lower()
return s2
From #RvdK analysis, you'ld have seen where corrections are needed. In addition to what has been pointed out, I want you to note that s[i] will work fine only if i is an integer, but in your case where (by assumption) i is a string you'll encounter several TypeErrors. From my understanding of what you want to do, it should go this way:
def to_weird_case(s):
for i in s:
if s.index(i) % 2 == 0:
s[s.index(i)] = i.upper() + s[s.index(i)]
elif s.index(i) % 2 == 1:
s[s.index(i)] = i.lower() + s[s.index(i)]
return i # or possibly return s
It is possible to do in a single line using a list comprehension
def funny_case(s):
return "".join([c.upper() if idx%2==0 else c.lower() for idx,c in enumerate(s)])
If you want to treat each word separately then you can split it up in to a list of words and "funny case" each word individually, see below code
original = "hello world"
def funny_case(s):
return "".join([c.upper() if idx%2==0 else c.lower() for idx,c in enumerate(s) ])
def funny_case_by_word(s):
return " ".join((funny_case(word) for word in s.split()))
print(funny_case_by_word(original))
Corrected code is as follows
def case(s):
txt=''
for i in range(len(s)):
if i%2==0:
txt+=s[i].upper()
else:
txt+=s[i].lower()
return txt
String assignment gives error in Python therefore i recommend considering my approach
When looping over elements of s, you get the letter itself, not its index. You can use enumerate to get both index and letter.
def to_weird_case(s):
result = ''
for index, letter in enumerate(s):
if index % 2 == 0:
result += letter.upper()
else:
result += letter.lower()
return result
correct code:
def to_weird_case(s):
str2 = ""
s.split() # through splitting string is converted to list as it is easy to traverse through list
for i in range(0,len(s)):
n = s[i] # storing value in n
if(i % 2 == 0):
str2 = str2 + n.upper()
else:
str2 = str2 + n.lower()
return str2
str1 = "hello world"
r = to_weird_case(str1)
print(r)
I have the task to write a program in which the user inputs 8 words, after which the program prints the longest word inputed and counts the length of the word. I'm having problems with finding the longest inputed string. Here's my code:
counter = 0
for i in range(8):
x = str(input('Enter a word: '))
counter = len(x)
if counter == max(counter):
print('The longest word is: ', counter)
which of course doesn't work.
max can take an argument key which is applied to each element:
words = [raw_input('Enter a word: ') for _ in xrange(8)]
max_word = max(words, key=len)
This ought to do it - this sorts the list using the 'len' operator to obtain the length of each string, and [-1] just picks the last (the longest) one.
words = []
for i in range(8):
words.append(raw_input('Enter a word: '))
longestWord = sorted(words, key=len)[-1]
print 'The longest word is %s (%s character%s)' % (longestWord, len(longestWord), len(longestWord) != 1 and 's' or '')
Mind you it is somewhat inefficient in that it stores all inputs in the array until the loop is over. Maybe better would be this:
longestWord = ''
for i in range(8):
word = raw_input('Enter a word: ')
if len(word) > len(longestWord):
longestWord = word
print 'The longest word is %s (%s character%s)' % (longestWord, len(longestWord), len(longestWord) != 1 and 's' or '')
Consider keeping the lengths in a list and finding the max value in that list.
counter=""
for i in range(8):
x=str(input('Enter a word: '))
if len(counter) < len(x):
counter = x
print('The longest word is: ',x)
I want to create a function in Python, where input will be the String and input it into an array to be returned.
For example:
Input: "The dog is red"
Output: "The", "dog", "is", "red"
I believe the algorithm should work, but nothing is returned. From what I can assume, the if statement is not detecting the space ( ").
The code is below:
string = input("Input here:")
def token(string):
start = 0
i = 0
token_list = []
for x in range(0, len(string)):
if " " == string[i:i+1]:
token_list = token_list + string[start:i+1]
print string[start:i+1]
start = i + 1
i += 1
return token_list
You can simply split the string.
result=input.split(" ")
or
string = raw_input("Input here:")
def token(string):
start = 0
i = 0
token_list = []
for x in range(0, len(string)):
if " " == string[i:i+1][0]:
token_list.append(string[start:i+1])
#print string[start:i+1]
start = i + 1
i += 1
token_list.append(string[start:i+1])
return token_list
print token(string)
You can modify your function to look like this:
string = input("Input here:")
def token(string):
start, i = 0, 0
token_list = []
for x in range(0, len(string)):
if " " == string[i:i+1]:
token_list.append(string[start:i+1])
start = i + 1
i += 1
token_list.append(string[start:i+1])
return token_list
print token(string)
You need to append only up until i if you don't want to include the trailing space. The second append is necessary because your condition is checking for a space to include the word, but the last word won't have a trailing space, and instead would have an end of line character or null.
So I was doing our exercise when I came across capitalizing characters in odd indices. I tried this:
for i in word:
if i % 2 != 0:
word[i] = word[i].capitalize()
else:
word[i] = word[i]
However, it ends up showing an error saying that not all strings can be converted. Can you help me debug this code snippet?
The problem is strings in python are immutable and you cannot change individual characters. Apart fro that when you iterate through a string you iterate over the characters and not the indices. So you need to use a different approach
A work around is
(using enumerate)
for i,v in enumerate(word):
if i % 2 != 0:
word2+= v.upper()
# Can be word2+=v.capitalize() in your case
# only as your text is only one character long.
else:
word2+= v
Using lists
wordlist = list(word)
for i,v in enumerate(wordlist):
if i % 2 != 0:
wordlist[i]= v.upper()
# Can be wordlist[i]=v.capitalize() in your case
# only as your text is only one character long.
word2 = "".join(wordlist)
A short note on capitalize and upper.
From the docs capitalize
Return a copy of the string with its first character capitalized and the rest lowercased.
So you need to use upper instead.
Return a copy of the string with all the cased characters converted to uppercase.
But in your case both work accurately. Or as Padraic puts it across "there is pretty much no difference in this example efficiency or output wise"
You need enumerate and capitalise any character at any odd i where i is the index of each char in the word:
word = "foobar"
print("".join( ch.upper() if i % 2 else ch for i, ch in enumerate(word)))
fOoBaR
ch.upper() if i % 2 else ch is a conditional expression where we change the char if the condition is True or else leave as is.
You cannot i % 2 when i is the actual character from the string, you would need to use range in your code or use enumerate and concatenate the changed characters to an output string or make words a list.
Using a list you can use assignment:
word = "foobar"
word = list(word)
for i, ele in enumerate(word):
if i % 2:
word[i] = ele.upper()
print("".join(word))
Using an output string:
word = "foobar"
out = ""
for i, ele in enumerate(word):
if i % 2:
out += ele.upper()
else:
out += ele
if i % 2: is the same as writing if i % 2 != 0.
This is how I would change word letters in a word or a sentence to uppercase
word = "tester"
letter_count = 1
new_word = []
for ch in word:
if not letter_count % 2 == 0:
new_word.append(ch.upper())
else:
new_word.append(ch)
letter_count += 1
print "".join(new_word)
if I wanted to change odd words in a sentence to uppercase I would do this
sentence = "this is a how we change odd words to uppercase"
sentence_count = 1
new_sentence = []
for word in sentence.split():
if not sentence_count % 2 == 0:
new_sentence.append(word.title() + " ")
else:
new_sentence.append(word + " ")
sentence_count += 1
print "".join(new_sentence)
I think it will help...
s = input("enter a string : ")
for i in range(0,len(s)):
if(i%2!=0):
s = s.replace(s[i],s[i].upper())
print(s)