Home > Mobile >  How to remove space from variable and put a character instead of space in python?
How to remove space from variable and put a character instead of space in python?

Time:11-04

My Python code looks like

name = 'my full name'

And i wanna print this texts be like

https://example.com/?s=my full name

So How can i remove space and put that ' '?

I want the example code and with explanation if possible.

CodePudding user response:

Also you can write like this

name="my full name"
name1=[] #To store the string(modified)
for _ in range(len(name)):
    if name[_]==' ': #condition 
   name1.remove(name[_-1])#removes the last appended element


name1.append(name[_-1] " ")#appends concatenate last element with ' '
else:
    name1.append(name[_])
print("".join(name1)) 

CodePudding user response:

A few options:

  1. Use urllib parse:
import urllib.parse

url = 'https://example.com/?s='   urllib.parse.quote_plus('my full name')
  1. Replace spaces with and concatenate to URL.
name = 'my full name'
url = 'https://example.com/?s='   name.replace(' ', ' ')
  1. Use split and concatenate the list indices:
name = 'my full name'
name = name.split(' ')
url = 'https://example.com/?s='   name[0]   ' '   name[1]    ' '   name[2]

Output:

https://example.com/?s=my full name
  • Related