cutting a string at spaces python - string

I am beginning to learn python and want to cut a string at the spaces; so 'hello world' becomes 'hello' and 'world'. To do this i want to save the locations of the spaces in a list, but i can't figure out how to do this. In order to find the spaces i do this:
def string_splitting(text):
i = 0
for i in range(len(text)):
if (text[i]==' '):
After saving them in the list i want to display them with text[:list[1]] (or something like that)
Can anyone help me with the saving it in a list part; and is this even possible?
(Another way to cut the string is welcome to :-) )
Thanks.

Use split:
"hello world my name is".split(' ')
It will give you a list of strings

thanks, i tried to do it without the split option, should have said that in the question..
anyways this worked;
def split_stringj(text):
a = text.count(' ')
p = len(text)
l = [-1]
x = 0
y = 1
for x in range(p):
if (text[x]==' '):
l.append(x)
y += 1
l.append(p)
print l
for x in range(len(l)-1):
print text[l[x]+1:l[x+1]]

Related

How to solve an a+b equation?

New to python, what am i doing wrong here that it wont print my total out?
second = 2
third = 3
extra = input("what is the extra value?")
total = ("first+second+thrid+extra")
print("total,")
You are printing a string by putting in double quotes
Whereas expression should be like this:
result = first + second + extra
print(result) # without quotes

How to convert a string looking like a list to list of floats?

I have this list:
s = '[ 0.00889175 -0.04808848 0.06218296 0.06312469 -0.00700571\n -0.08287739]'
it contains a '\n' character, I want to convert it to a list of float like this:
l = [0.00889175, -0.04808848, 0.06218296, 0.06312469, -0.00700571, -0.08287739]
I tried this code, which is close to what I want:
l = [x.replace('\n','').strip(' []') for x in s.split(',')]
but it still keeps quotes that I didn't manage to remove (i tried str.replace("'","") but it didn't work), this is what I get:
['0.00889175 -0.04808848 0.06218296 0.06312469 -0.00700571 -0.08287739']
You were quite close. This will work:
s = '[ 0.00889175 -0.04808848 0.06218296 0.06312469 -0.00700571\n -0.08287739]'
l = [float(n) for n in s.strip("[]").split()]
print(l)
Output:
[0.00889175, -0.04808848, 0.06218296, 0.06312469, -0.00700571, -0.08287739]
First thing needs to cleared that if you are keeping the str then there will be quotes unless you typecast each of element of your str by splitting it.
Following is my solution to your problem:
s='[ 0.00889175 -0.04808848 0.06218296 0.06312469 -0.00700571\n -0.08287739]'
#removing newline \n
new_str = s.replace('\n', '')
#stripping the brackets and extra space
new_str = new_str.strip(' []')
#splitting elements into a list
list_of_floats = new_str.split()
#typecasting from str to float
for _i, element in enumerate(list_of_floats):
list_of_floats[_i] = float(element)
print(list_of_floats)
#output
#[0.00889175, -0.04808848, 0.06218296, 0.06312469, -0.00700571, -0.08287739]

Python lists and ranges

I'm trying to practice my python so I can improve. I'm kinda stuck and not sure how to proceed. I get an error saying "can only concatenate list(not 'int') to list." I'll leave my code and what I'm trying to do below.
Input a word string (word)
find the string length of word
use range() to iterate through each letter in word (can use to range loops)
Save odd and even letters from the word as lists
odd_letters: starting at index 0,2,...
even_letters: starting at index 1,3,...
print odd and even lists
word = input("Type: ")
word = list(word)
print(word)
odd_letters = []
even_letters = []
length = int(len(word))
for i in range(length):
if i/2 == 0:
even_letters = even_letters + i
elif i/2 != 0:
odd_letters = odd_letters + i
print(even_letters)
print(odd_letters)
I wrote this... Let me know what you think...
word = input("Choose a word to test: ")
word_len = len(word)
print(word," contains ",word_len," letters")
odd_letters = []
even_letters = []
for i in range(1,len(word),2):
even_letters.append(word[i])
for i in range(0,word_len,2):
odd_letters.append(word[i])
print("Odd letters are: ",odd_letters)
print("Even letters are: ",even_letters)
Your code is good, but i decided to find a quicker solution for the program you want. This is my code:
word = str(input("Enter word:"))
store_1 = [x for x in word]
store_2 = []
for idx, val in enumerate(store_1):
store_2.append(idx)
even_numbers = [y for y in store_2 if y%2 == 0]
odd_numbers = [z for z in store_2 if z%2 == 1]
print("List of Even numbers:",even_numbers)
print("List of Odd numbers:",odd_numbers)
The variable 'word' takes in the word from the user. The list 'store_1' uses list comprehension to separate the letters the in the word and store it. Next, i enumerate through 'store_1' and use the variable 'store_2' to only store the indexes of 'store_1'.
Next, I declare another variable 'even_numbers' that uses list comprehension to iterate through 'store_2' and find the even numbers. The next variable 'odd_numbers' also uses list comprehension to find the odd numbers in 'store_2'.
Then, it just prints the even and odd lists to the user. Hope this helps :)
You cannot add an integer to a list, as you have attempted to do here:
even_letters = even_letters + i
You can instead do this (which is now adding a list to a list, which is valid):
even_letters = even_letters + [i]
Or, use append to alter the list in-place, adding the new element to the end:
even_letters.append(i)
Few things:
You cannot "add" an integer directly to a list using '+'. Using append() would be best.
str and str types can be concatenated using '+' so you could change odd_letters and even_letters to str as shown below.
also, by adding 'i' to even and odd, you are adding the iteration variable value.
Since you want the letter to be appended, you need to refer the list index i.e word[i]
and the first letter of what is entered will be at an odd position :)
word = input("Type: ")
word = list(word)
print(word)
odd_letters = ''
even_letters = ''
length = int(len(word))
for i in range(1,length+1):
if i%2 == 0:
even_letters = even_letters + word[i-1]
else:
odd_letters = odd_letters + word[i-1]
print("even_letters",even_letters)
print("odd_letters",odd_letters)
word=input()
word_num=len(word)
print(word_num)
odd_num=[]
even_num=[]
for letters in range(0,word_num,2):
odd_num.append(word[letters])
for letters in range(1,word_num,2):
even_num.append(word[letters])
print(odd_num)
print(even_num)
This is the answer it works with every word, and follows all the requirements.

String search keep returning empty in python

I have kept trying to get my code to work but I keep getting blank output and I am not allowed to import anything e.g. RE:
choc1 =' outf.write("/# " + str(number) + " #/ " + line) #lots of cake(#) lovers here'
EC = choc1
ECout = EC
out = ""
for x in ECout :
if x!="#[a-z,A-Z]":
x = x.replace(x,"")
out += x
if out== '#lots of cake(#) lovers here':
print("well done Lucy")
else:
print(out)
I must be really stupid as this should be simple - I need to return '#lots of cake(#) lovers here' but I'm stuck on this assignment.
Any help would be greatly appreciated.
Thanks in advance - Jemma
Looking at your for loop, you are examining each character in a string individually, and comparing this to a string that is several characters long. Is this what you intended? Consider:
>>> a = "abc"
>>> for x in a:
... print(x)
...
a
b
c
Perhaps you meant to take each character, and compare that character to each character separately in the other string with a slightly different statement?

How to do a backspace in python

I'm trying to figure out how to print a one line string while using a for loop. If there are other ways that you know of, I would appreciate the help. Thank you. Also, try edit off my code!
times = int(input("Enter a number: "))
print(times)
a = 0
for i in range(times+1):
print("*"*i)
a += i
print("Total stars: ")
print(a)
print("Equation: ")
for e in range(1,times+1):
print(e)
if e != times:
print("+")
else:
pass
Out:
Enter a number: 5
*
**
***
****
*****
Equation:
1
+
2
+
3
+
4
+
5
How do I make the equation in just one single line like this:
1+2+3+4+5
I don't think you can do a "backspace" after you've printed. At least erasing from the terminal isn't going to be done very easily. But you can build the string before you print it:
times = int(input("Enter a number: "))
print(times)
a = 0
for i in range(times+1):
print("*"*i)
a += i
print("Total stars: ")
print(a)
print("Equation: ")
equation_string = ""
for e in range(1,times+1):
equation_string += str(e)
if e != times:
equation_string += "+"
else:
pass
print(equation_string)
Basically, what happens is you store the temporary equation in equation_str so it's built like this:
1
1+
1+2
1+2+
...
And then you print equation_str once it's completely built. The output of the modified program is this
Enter a number: 5
5
*
**
***
****
*****
Total stars:
15
Equation:
1+2+3+4+5
Feel free to post a comment if anything is unclear.
Instead of your original for loop to print each number, try this:
output = '+'.join([str(i) for i in range(1, times + 1)])
print(output)
Explanation:
[str(i) for i in range(1, times + 1)] is a list comprehension that returns a list of all your numbers, converted to strings so that we can print them.
'+'.join(...) joins each element of your list, with a + in between each element.
Alternatively:
If you want a simple modification to your original code, you can simply suppress the newline from each print statement with the keyword paramater end, and set this to an empty string:
print(e, end='')
(Note that I am addressed the implied question, not the 'how do I do a backspace' question)
Too long for a comment, so I will post here.
The formatting options of python can come into good use, if you have a sequence you wish to format and print.
Consider the following...
>>> num = 5 # number of numbers to generate
>>> n = num-1 # one less used in generating format string
>>> times = [i for i in range(1,num+1)] # generate your numbers
>>> ("{}+"*n + "{}=").format(*times) # format your outputs
'1+2+3+4+5='
So although this doesn't answer your question, you can see that list comprehensions can be brought into play to generate your list of values, which can then be used in the format generation. The format string can also be produced with a l.c. but it gets pretty messy when you want to incorporate string elements like the + and = as shown in the above example.
I think you are looking for the end parameter for the print function - i.e. print(e, end='') which prints each value of e as it arrives followed by no space or newline.

Resources