Home > Back-end >  Replace space with underscores python string -
Replace space with underscores python string -

Time:10-28

file = 'file1 data ut.pdf'

print(file)
print(type(file))

'file1 data ut.pdf'
<class 'str'>

file.replace(" ","_")

'_f_i_l_e_1_ _d_a_t_a_ _u_t_._p_d_f'

file.replace("","_")

Expected output:

file1_data_ut.pdf

CodePudding user response:

I am not certain why file.replace(" ","_") does not work for you. You can alternatively try this code:

>>> file = 'file1 data ut.pdf'
>>> '_'.join(file.split())
'file1_data_ut.pdf'

In essence, str.split returns a list of the words in the string, using sep as the delimiter string. The default value of sep is ' '. str.join returns a string which is the concatenation of the strings in a collection, in this case, the collection is the list generated by str.split.

CodePudding user response:

I don't know why replace on your side is not working.

TRY this.

file = 'file1 data ut.pdf'


print('_'.join(file.split(' ')))

OUTPUT

file1_data_ut.pdf

Explanation

  1. file.split(' ') convert string to list by given operator.

['file1', 'data', 'ut.pdf']

  1. '_'.join() concatenate all the strings in the list and add '_' given string between them.

'file1_data_ut.pdf'

CodePudding user response:

file.replace(" ", "_") 

CodePudding user response:

You need to store the updated string in the new variable.

file = 'file1 data ut.pdf'

print(file)
print(type(file))

file=file.replace(" ","_")
  • Related