How to remove spaces after comma in python? - python

odd_integer = int(input())
integer_list = []
for i in range(0,odd_integer):
rand_int = int(input())
integer_list.append(rand_int)
integer_list.reverse()
middle_value = int(len(integer_list)/2)
print(f"{integer_list[0:middle_value]}-[{integer_list[middle_value]}]-{integer_list[middle_value+1:]}")
answer is [2, 5]-[4]-[3, 1]
but it should be [2,5]-[4]-[3,1]

You can use replace() in your string
For example:
your_string.replace(", ", ",")
Where according to your question only the ", " (comma followed by space) is replaced by "," (comma).

This is due to your print statement. What you can do is first assign it to a variable, replace the spaces and then print it.
The replace and print can be combined since replace returns the new string.
So basically:
output = f"{integer_list[0:middle_value]}-[{integer_list[middle_value]}]-{integer_list[middle_value+1:]}"
print(output.replace(" ", "")

the space after the coma is the standard representation when you print an array.
try to simply print([1,2]) you will have the same result.
if you really need no space you have to rewrite the way to display the array.
for example like this :
print(f"{','.join(map(str,integer_list[0:middle_value]))}-[{integer_list[middle_value]}]-{','.join(map(str,integer_list[middle_value+1:]))}")
join function will merge into a string with comma separated as noted, the map function will cast the int into str.

remove multiple space python
import re
re.sub(' +', ' ', 'hello hi there')
'hello hi there'
remove after and before space python
st = " a "
strip(st)
#Output : "a"

Related

Python - Why is len() always return 1 for list

Not sure why len() is returning just 1 as output in Python. Should be 4.
names_string = input("Give me everybody's names, separated by a comma. ")
names = names_string.split(", ")
num_items = len(names)
print(num_items,",",names,type(names))
Output
Give me everybody's names, separated by a comma. angel,barbara,mary,jjjj
1, ['angel,barbara,mary,jjjj'] <class 'list'>
In your input string ('angel,barbara,mary,jjjj') names are separated with commas without spaces (','), but you try to split it by comma and space (', '). There is no ', ' in the string, so it's not split
You are splitting the input on , . remove the space.
the problem with your code is that there isn't a way to split like this ", ". the correct way to do so is by removing the space and split like ","
this is the correct code:
names_string = input("Give me everybody's names, separated by a comma. ")
names = names_string.split(",")
num_items = len(names)
print(num_items,",",names,type(names))
You need to split by "," or separate your input with comma and space.

I want to replace all the spaces with "-"

I want to replace all the spaces with "-".
This is my code:
print("enter movie name with dashes in spaces,all under case")
print("like this for example")
print("django-unchained")
b=0
a=input("enter movie name now : ")
y=input("Release year? : ")
for x in range (0,len(a)):
if a[b].isspace():
a[b]="-"
b+=1
All it says is:
TypeError: 'str' object does not support item assignment
In Python, strings are not mutable. In other words, Python does not directly allow you to treat a string as an array of characters. When you use a[b], you are retrieving the character at a specific index, not addressing the element in an array. Here are a couple options:
Use replace
new_string = a.replace(' ', '-')
This is the easiest approach to get the outcome you described. If this was a simplified example and you wanted to index the array for a particular reason, try the next option.
Convert to a list
new_list = list(a)
You can now modify the individual characters in the list, similar to your original approach.
In Python, strings are not mutable, which means they cannot be changed.
You can use replace() instead:
a = a.replace(' ', '-')
You can do something like this :
a=input("enter movie name now : ").replace(" ", "-")
y= input("Release year? : ").replace(" ", "-")
print(a)
print(y)

Printing every other letters of a string without the spaces on Python

I am trying to build a function that will take a string and print every other letter of the string, but it has to be without the spaces.
For example:
def PrintString(string1):
for i in range(0, len(string1)):
if i%2==0:
print(string1[i], sep="")
PrintString('My Name is Sumit')
It shows the output:
M
a
e
i
u
i
But I don't want the spaces. Any help would be appreciated.
Use stepsize string1[::2] to iterate over every 2nd character from string and ignore if it is " "
def PrintString(string1):
print("".join([i for i in string1[::2] if i!=" "]))
PrintString('My Name is Sumit')
Remove all the spaces before you do the loop.
And there's no need to test i%2 in the loop. Use a slice that returns every other character.
def PrintString(string1):
string1 = string1.replace(' ', '')
print(string1[::2])
Replace all the spaces and get every other letter
def PrintString(string1):
return print(string1.replace(" ", "") [::2])
PrintString('My Name is Sumit')
It depends if you want to first remove the spaces and then pick every second letter or take every second letter and print it, unless it is a space:
s = "My name is Summit"
print(s.replace(" ", "")[::2])
print(''.join([ch for ch in s[::2] if ch != " "]))
Prints:
MnmiSmi
Maeiumt
You could alway create a quick function for it where you just simply replace the spaces with an empty string instead.
Example
def remove(string):
return string.replace(" ", "")
There's a lot of different approaches to this problem. This thread explains it pretty well in my opinion: https://www.geeksforgeeks.org/python-remove-spaces-from-a-string/

Why am I getting different results when I use splitted string parts using string.split(' ') and string[:-1] during itertoools.permutations() usag?

What's the difference between:
stringline = string.split(' ')
int_part = int(stringline[1])
string_part = stringline[0]
and
string_part = string[:-1]
int_part = int(string[-1:])
where stringline = "HACK 2" ?
I believed both were the same but when I try to use them to print list elements using itertools.permutations(), I get different results.
string[:-1] just removes the very last character and gives you "HACK " (notice the space) whereas string.split(" ")[0] gives you the element "HACK" (notice no space).
That's because split also removes the space from the original string and returns a list of ["HACK", "2"], whereas string[:-1] just stop return characters at "2".
It is simply because string_part = string[:-1] gives 'HACK ' with space, so itertools.permutations() will count the space in the iterable as well.

How do I convert a list into a string with spaces in Python?

How can I convert a list into a space-separated string in Python?
For example, I want to convert this list:
my_list = ["how", "are", "you"]
into the string "how are you".
The spaces are important. I don't want to get "howareyou".
" ".join(my_list)
You need to join with a space, not an empty string.
I'll throw this in as an alternative just for the heck of it, even though it's pretty much useless when compared to " ".join(my_list) for strings. For non-strings (such as an array of ints) this may be better:
" ".join(str(item) for item in my_list)
For Non String list we can do like this as well
" ".join(map(str, my_list))
So in order to achieve a desired output, we should first know how the function works.
The syntax for join() method as described in the python documentation is as follows:
string_name.join(iterable)
Things to be noted:
It returns a string concatenated with the elements of iterable. The separator between the elements being the string_name.
Any non-string value in the iterable will raise a TypeError
Now, to add white spaces, we just need to replace the string_name with a " " or a ' ' both of them will work and place the iterable that we want to concatenate.
So, our function will look something like this:
' '.join(my_list)
But, what if we want to add a particular number of white spaces in between our elements in the iterable ?
We need to add this:
str(number*" ").join(iterable)
here, the number will be a user input.
So, for example if number=4.
Then, the output of str(4*" ").join(my_list) will be how are you, so in between every word there are 4 white spaces.
you can iterate through it to do it
my_list = ['how', 'are', 'you']
my_string = " "
for a in my_list:
my_string = my_string + ' ' + a
print(my_string)
output is
how are you
you can strip it to get
how are you
like this
my_list = ['how', 'are', 'you']
my_string = " "
for a in my_list:
my_string = my_string + ' ' + a
print(my_string.strip())
Why don't you add a space in the items of the list itself, like :
list = ["how ", "are ", "you "]

Categories