QBoard » Artificial Intelligence & ML » AI and ML - Python » How to join() words from a string?

How to join() words from a string?

  • 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?
      October 13, 2021 1:45 PM IST
    0
  • You can also split/join:

    '_'.join('one two three'.split())
    
      October 15, 2021 1:55 PM IST
    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".

      October 16, 2021 12:51 PM IST
    0
  • 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).
      October 18, 2021 1:55 PM IST
    0
  • The join() method takes iterable – objects capable of returning their members one at a time. Some examples are List, Tuple, String, Dictionary, and Set

    Return Value: 

    The join() method returns a string concatenated with the elements of iterable

    Type Error:

    If the iterable contains any non-string values, it raises a TypeError exception. 

    # Python program to demonstrate the
    # use of join function to join list
    # elements with a character.
    
    list1 = ['1','2','3','4']
    
    s = "-"
    
    # joins elements of list1 by '-'
    # and stores in sting s
    s = s.join(list1)
    
    # join use to join a list of
    # strings to a separator s
    print(s)
    
      December 21, 2021 1:48 PM IST
    0