If I have a string 'banana peel' and I want to break it down to a width of 3 characters as in:
'ban'
'ana'
'pee'
'l'
How would I go about that? How would I remove the space/whitespace between 'banana' and 'peel' that is in the middle of the string and create the results above?
Only things that come to mind are things like list() and strip()
Just like this:
string = "banana peel"
string = string.replace(" ", "")
results = []
for i in range(0, len(string), 3):
results.append(string[i:i + 3])
print(results)
replace(" ", "") replaces all the spaces with nothing, giving bananapeel. range(0, len(string), 3) will give a list of numbers from 0 to the length of the string with an interval of 3. Each set gets added to the array for you to print in the end.
Related
Whenever I put a string, it's supposed to take the capital letters' index and put it into a list, but when the string is 10 characters or longer and it has a capital letter after the ninth index, it separates the number when it gets added to the 'capitals' list. How do I make it so it doesn't separate?
string = input()
capitals = []
for current in range(0, len(string)):
if string[current].isupper():
capitals += str(current)
print([int(x) for x in capitals])
short research would help you. here is your answer:
Python append() vs. + operator on lists, why do these give different results?
TL;DR:
using + operator adds elements of an array separately, .append adds array itself
You can simply add the integers directly without calling str:
string = 'hello darkness my Old Friend'
capitals = []
for current in range(0, len(string)):
if string[current].isupper():
capitals += [current] # concatenate the lists
print(capitals) # [18, 22]
A better code:
string = 'hello darkness my Old Friend'
capitals = []
for i, char in enumerate(string):
if char.isupper():
capitals.append(i) # add index at the end
print(capitals) # [18, 22]
string = input()
capitals = []
for i, char in enumerate(string):
if char.isupper():
capitals.append(i)
print([int(x) for x in capitals])
I believe the short answer to getting your desired results would be to utilize the "append" function in lieu of performing a "+=". Following is a snippet of code.
string = input()
capitals = []
for current in range(0, len(string)):
if string[current].isupper():
capitals.append(str(current)) # Used append
print([int(x) for x in capitals])
Following was a sample test.
#Una:~/Python_Programs/Capitals$ python3 Capital.py
PeterPiperPickedaPeckofPickledPeppers
[0, 5, 10, 17, 23, 30]
Give that a try.
When you add the string variable to the list, Python first transform your string to the another list, which means it iterates the string over the letters. The most Pythonic way to do what you want is iterate over the string using list comprehension.
string = input()
capitals = [i for i, letter in enumerate(string) if letter.isupper()]
print(capitals)
It's because your use of +. Use append instead:
while True:
lst = []
string = input()
index = 0
for i in string:
if i.isupper():
lst.append(index)
index += 1
print(lst)
I want to print a string in reverse and build it by printing letter by letter.
E.g - Word is: string
Ideal output is:
g
gn
gni
gnir
gnirt
gnirts
I want the user to be able to enter any word not just "String"
Code I have tried:
text = input('Enter a string: ')
reversed_text = ''
last_index = len(text) - 1
for i in range(last_index, -1, -5):
for i in range(last_index, -1, -1):
for i in range(last_index, -1, -1):
reversed_text += text[i]
print(reversed_text)
s=input("Word: ")
r=''
for char in reversed(s):
r+=char
print(r)
print ("Reversed word is %s " % (r))
This is the code I used, it works thank you for the answers
s='string'
r=''
for char in reversed(s):
r+=char
print(r)
This code does what you're asking.
A simple way of doing this with user input should be something on these lines:
newstring = ""
enterString = (str(input("Enter a string to be reversed:")))
count = 0
for i in reversed(enterString):
newstring += i
count += 1
print ("Reversed string %s is this: %s" % (count, newstring))
Output with count of how many times till it gets the last character:
Enter a string to be reversed:hello
Reversed string 1 is this: o
Reversed string 2 is this: ol
Reversed string 3 is this: oll
Reversed string 4 is this: olle
Reversed string 5 is this: olleh
This solution uses extended slice to reverse the word segments and separate each with a space. Other answers have separated the reversed word segments with a newline. Just replace ' '.join with '\n'.join if you require this behavior.
word = 'string'
reversed = '\n'.join(word[-1:i:-1] for i in range(-2, -2 - len(word), -1))
print(reversed)
edit: Separated reversed word segments with newline to reflect updated question.
I am pretty new to python and would like to know how to write a program that asks the user to enter a string that contains the letter "a". Then, on the first line, the program should print the part of the string up to and including the certain letter, and on the second line should be the rest of the string.
For example...
Enter a word: Buffalo
Buffa
lo
This is what I have so far :
text = raw_input("Type something: ")
left_text = text.partition("a")[0]
print left_text
So, I have figured out the first part of printing the string all the way up to the certain letter but then don't know how to print the remaining part of the string.
Any help would be appreciated
If what you want is the first occurrence of a certain character, you can use str.find for that. Then, just cur the string into two pieces based on that index!
In python 3:
split_char = 'a'
text = input()
index = text.find(split_char)
left = text[:-index]
right = text[-index:]
print(left, '\n', right)
I don't have a python2 on hand to make sure, but I assume this should work on python 2:
split_char = 'a'
text = raw_input()
index = text.find(split_char)
left = text[:-index]
right = text[-index:]
print left + '\n' + right)
Another option that is far more concise is to use
left_text, sep, right_text = text.partition("a")
print (left_text + sep, '\n', right_text)
and then as suggested in the comments, thanks #AChampion !
You should have some knowledge about slicing and concatenating string or list. You can learn them here Slicing and Concatenating
word = raw_input('Enter word:') # raw_input in python 2.x and input in python 3.x
split_word = raw_input('Split at: ')
splitting = word.partition(split_word)
'''Here lets assume,
word = 'buffalo'
split_word = 'a'
Then, splitting variable returns list, storing three value,
['buff', 'a', 'lo']
To get your desire output you need to do some slicing and concatenate some value .
'''
output = '{}\n{}'.join(splitting[0] + splitting[1], splitting[2])
print(output)
First find the indices of the character in the given string, then print the string accordingly using the indices.
Python 3
string=input("Enter string")
def find(s, ch):
return [i for i, ltr in enumerate(s) if ltr == ch]
indices=find(string, "a")
for index in indices[::-1]:
print(string[:index+1])
print(string[indices[-1]+1:])
It's actually a string but I just converted it to a list because the answer is supposed to be returned as a list. I've been looking at this problem for hours now and cannot get it. I'm supposed to take a string, like "Mary had a little lamb" for example and another string such as "ab" for example and search through string1 seeing if any of the letters from string2 occur. So if done correctly with the two example it would return
["a=4","b=1"]
I have this so far:
def problem3(myString, charString):
myList = list(myString)
charList = list(charString)
count = 0
newList = []
newString = ""
for i in range(0,len(myList)):
for j in range(0,len(charList)):
if charList[j] == myList[i]:
count = count + 1
newString = charList[j] + "=" + str(count)
newList.append(newString)
return newList
Which returns [a=5] I know it's something with the newList.append(string) and where it should be placed, anyone have any suggestions?
You can do this very easily with list comprehensions and the count function that strings (and lists!) have:
Split the search string into a list of chars.
For each character in the search string, loop over the input string and determine how much it occurs (via count).
Example:
string = 'Mary had a little lamb'
search_string = 'ab'
search_string_chars = [char for char in search_string]
result = []
for char in search_string_chars:
result.append('%s=%d' % (char, string.count(char)))
Result:
['a=4', 'b=1']
Note that you don't need to split the search_string ('ab') into a list of characters, as strings are already lists of characters - the above was done that way to illustrate the concept. Hence, a reduced version of the above could be (which also yields the same result):
string = 'Mary had a little lamb'
search_string = 'ab'
result = []
for char in search_string:
result.append('%s=%d' % (char, string.count(char)))
Here's a possible solution using Counter as mentioned by coder,
from collections import Counter
s = "Mary had a little lambzzz"
cntr = Counter(s)
test_str = "abxyzzz"
results = []
for letter in test_str:
if letter in s:
occurrances = letter + "=" + str(cntr.get(letter))
else:
occurrances = letter + "=" + "0"
if occurrances not in results:
results.append(occurrances)
print(results)
output
['a=4', 'b=1', 'x=0', 'y=1', 'z=3']
import collections
def count_chars(s, chars):
counter = collections.Counter(s)
return ['{}={}'.format(char, counter[char]) for char in set(chars)]
That's all. Let Counter do the work of actually counting the characters in the string. Then create a list comprehension of format strings using the characters in chars. (chars should be a set and not a list so that if there are duplicate characters in chars, the output will only show one.)
it's a loop to reverse a string entered by the user, it reads letters in reverse and put them into a sentence. the problem is that, for example user's input is hello, the comma(,) in the last line of the code makes the output to be o l l e h, but if there isnt a comma there, the output will have each letter in a line. and concatenate (+) doesnt work it gives an error. What do i do so that the output would be olleh instead of o l l e h?
phrase = raw_input("Enter a phrase to reverse: ")
end = (len(phrase))-1
for index in range (end,-1,-1):
print phrase[index],
how about:
string = ''
for i in range(end, -1, -1):
string += phrase[i]
print string
However, an easier, cleaner way without the for loop is:
print phrase[::-1] # this prints the string in reverse
And also there is:
#As dougal pointed out below this is a better join
print ''.join(reversed(phrase))
#but this works too...
print ''.join(phrase[i] for i in range(end, -1, -1)) # joins letters in phrase together from back to front
To concatenate something, you have to have a string to concatenate to. In this case, you need a variable that is defined outside of the for loop so you can access it from within the for loop multiple times, like this:
phrase = raw_input("Enter a phrase to reverse: ")
end = (len(phrase))-1
mystr = ""
for index in range (end,-1,-1):
mystr += phrase[index]
print mystr
Note that you can also simply reverse a string in Python doing this:
reversedstr = mystr[::-1]
This is technically string slicing, using the third operator to reverse through the string.
Another possibility would be
reversedstr = ''.join(reversed(mystr))
reversed returns a reversed iterator of the iterator you passed it, meaning that you have to transform it back into a string using ''.join