1

I want to transform the string 'one two three' into one_two_three.

I've tried "_".join('one two three'), but that gives me o_n_e_ _t_w_o_ _t_h_r_e_e_...

how do I insert the "_" only at spaces between words in a string?

martineau
  • 119,623
  • 25
  • 170
  • 301
8-Bit Borges
  • 9,643
  • 29
  • 101
  • 198

3 Answers3

10

You can use string's replace method:

'one two three'.replace(' ', '_')
# 'one_two_three'

str.join method takes an iterable as an argument and concatenate the strings in the iterable, string by itself is an iterable so you will separate each character by the _ you specified, if you directly call _.join(some string).

Psidom
  • 209,562
  • 33
  • 339
  • 356
5

You can also split/join:

'_'.join('one two three'.split())
saarrrr
  • 2,754
  • 1
  • 16
  • 26
0

And if you want to use join only , so you can do like thistest="test string".split() "_".join(test) This will give you output as "test_string".

Johnny
  • 117
  • 1
  • 9