I want to replace all the spaces with "-" - python

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)

Related

How to remove spaces after comma in 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"

How to convert a vertical string to a horizontal one?

how can I convert a vertical string into a horizontal one in Python?
I tried:
result=astring.replace("\n", "")
but it doesn't do anything, it remains vertical..
The code is the following:
names = "".join(name).replace("\n","")
print(names)
where "names" is:
Federica
Silvio
Enrico
I would like:
Federica, Silvio, Enrico
x = """Federica
Silvio
Enrico"""
x.replace("\n",', ')
'Federica, Silvio, Enrico'
Your method is fundamentally wrong, when you apply a function, it combines a iterables with spaces in the middle. e.g.
" ".join("hello")
'h e l l o'
So when you call it on a string with no join value, the string is unchanged. Then you replace '\n' with '', which will flatten the string but not insert the comma.
If you have the names in a string format, for example:
names = """Federica
Silvio
Enrico"""
You can split the vertical string into an horizontal string using replace:
result = names.replace("\n", ", ")
Which results in:
print(results)
'Federica, Silvio, Enrico'
From this, I can say your approach was not wrong, maybe you were not storing the result of the replace? Replace does not modify the string but returns a new one with the operation performed.

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/

How to skip comma and space, but not changing the value

I just start learning python, and would like to ask the reader to input a number,but i would like to skip comma and space that reader input.
a = input("input a number:")
x = y
print(dec(x))
However, if i use split, it would become a list or 2 number
for example, when user input 12,3456,
and y would become ['12', '3456']
And my expected output is 123456 as a integer but not a list with two values.
I tried to use replace before, but it said
"TypeError: object of type 'int' has no len()"
Instead of using split, you can just use replace to remove any comma or space from the string you read from input.
a=input("input a number:")
a = a.replace(",","").replace(" ","")
print(a)
You could try something like this.
>>> number = int("".join(input().split(',')))
12,3456
>>> number
123456
>>>
Basically just splitting the input based on ',' and then joining them
You could also try replacing the ',' with ''
>>> number = int(input().replace(',',''))
12,3456
>>> number
123456
>>>
Hope this helps!

Make an input string into a list in python

I want to turn the string:
avengers,ironman,spiderman,hulk
into the list:
['avengers','ironman','spiderman','hulk']
I tried
list = raw_input("Enter string:")
list = list.split()
but it's not working the right way as I need it, it's taking the whole string and makes it as one item in the list (it works fine without the "," but that's not what I need)
If you dont pass anything to split method, it splits on empty space. Pass the comma as argument:
my_list.split(',')
edited so you dont use list as name
Hello guys i want to make for example the next string:
avengers,ironman,spiderman,hulk into the next list:
['avengers','ironman','spiderman','hulk']
i tried that `
list = raw_input("Enter string:")
list = list.split()
Do this instead:
list = raw_input("Enter string:")
list = list.split(",")
And, as mentioned by the others, you might want to not use the name "list" for your string/array.

Categories