'How to remove a space/whitespace from a string while concatenate operation in Python

I have this:

print('abcd'+'_',cariable)

which gives me this:

abcd_ 2021_mc.txt

But i need this : abcd_2021_mc.txt i.e. no space between _ and 2.

Can anybody suggest me on this. it would be of a great HELP !! thanks in Advance :)



Solution 1:[1]

If the variable cariable is a string then you can do string concatenation directly and just do print('abcd'+'_'+cariable). That should result in abcd_2021_mc.txt.

Solution 2:[2]

You can control the separator used by print using the sep parameter.

>>> print('abcd','2021_mc.txt', sep='')
abcd2021_mc.txt
>>> 

Solution 3:[3]

You can build string using the + operator:

a = '_' + '2021'

Solution 4:[4]

This gives you what you want:

print('abcd' + '_' + cariable)

Solution 5:[5]

You can use sep argument for print function.

print("abcd", cariable, sep='_')

Solution 6:[6]

I am not sure why you are concatenating 'abcd' and '_' when the results are clearly 'abcd_'.

When you print multiple fields, the default separator is a space. But you can override that. I can only deduce that cariable is '2021_mc.txt', so:

print('abcd', '_', cariable, sep='') # no space between 'abcd', '_', and cariable
#or:
print('abcd_', cariable, sep='')
#or:
print('abcd' + '_', cariable, sep='')

Update

>>> cariable = '2021_mc.txt'
>>> print('abcd', '_', cariable, sep='') # no space between 'abcd', '_', and cariable
abcd_2021_mc.txt
>>> #or:
>>> print('abcd_', cariable, sep='')
abcd_2021_mc.txt
>>> #or:
>>> print('abcd' + '_', cariable, sep='')
abcd_2021_mc.txt
>>>

Solution 7:[7]

Using f-strings:

print(f"abcd_{cariable}")

If you need to have "abcd" and "_" separated:

s = "abcd"
print(f"{s}_{cariable}")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bob Swinkels
Solution 2 snakecharmerb
Solution 3 Oily
Solution 4 Henrik
Solution 5 Hook
Solution 6
Solution 7 iasonast