bbesase
bbesase

Reputation: 861

Adding a simple value to a string

If I have a string lets say ohh

path2 = '"C:\\Users\\bgbesase\\Documents\\Brent\\Code\\Visual Studio' 

And I want to add a " at the end of the string how do I do that? Right now I have it like this.

path2 = '"C:\\Users\\bgbesase\\Documents\\Brent\\Code\\Visual Studio'
w = '"'
final = os.path.join(path2, w)
print final

However when it prints it out, this is what is returned:

"C:\Users\bgbesase\Documents\Brent\Code\Visual Studio\"

I don't need the \ I only want the "

Thanks for any help in advance.

Upvotes: 2

Views: 158

Answers (4)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251011

I think the path2+w is the simplest answer here but you can also use string formatting to make it more readable:

>>> path2 = '"C:\\Users\\bgbesase\\Documents\\Brent\\Code\\Visual Studio' 
>>> '{}"'.format(path2)
'"C:\\Users\\bgbesase\\Documents\\Brent\\Code\\Visual Studio"'

If path2 was long than it's much easier to use string formatting than adding a + at the end of the string.

>>> path2 = '"C:\\Users\\bgbesase\\Documents\\Brent\\Code\\Visual Studio\\Documents\\Brent\\Code\\Visual Studio\\Documents\\Brent\\Code\\Visual Studio'
>>> w = '"'
>>> "{}{}".format(path2,w)
'"C:\\Users\\bgbesase\\Documents\\Brent\\Code\\Visual Studio\\Documents\\Brent\\Code\\Visual Studio\\Documents\\Brent\\Code\\Visual Studio"'

Upvotes: 2

Gus E
Gus E

Reputation: 2219

just do:

path2 = '"C:\\Users\\bgbesase\\Documents\\Brent\\Code\\Visual Studio' + '"'

Upvotes: 7

artdanil
artdanil

Reputation: 5082

From Python documentation Common pathname manipulations section:

The return value is the concatenation of path1, and optionally path2, etc., with exactly one directory separator (os.sep) following each non-empty part except the last.

In this case, os.path.join() treats your string '"' as path part and adds the separator. Since you are not joining two parts of path you need to use string concatenation or string formatting.
The simplest would be just to add two strings:

final = path2 + '"'

You can actually modify path2 using += operator:

path2 += '"'

Upvotes: 0

Theo Belaire
Theo Belaire

Reputation: 3020

How about?

path2 = '"C:\\Users\\bgbesase\\Documents\\Brent\\Code\\Visual Studio' + '"'

Or, as you had it

final = path2 + w

It's also worth mentioning that you can use raw strings (r'stuff') to avoid having to escape backslashes. Ex.

path2 = r'"C:\Users\bgbesase\Documents\Brent\Code\Visual Studio'

Upvotes: 7

Related Questions