How do I add a "/" to the beginning and ending of a string in python? For example:
Input: test
Output: /test/
Input: /test
Output: /test/
Input: test/
Ouput: /test/
What's a neat way to do this? The only way I could think of was writing different if statements for each case. Surely, there's a better way to do this?
Strip off any slashes from the existing string, then put two new ones around that.
text = "/%s/" % text.strip("/")
Remove the old '/'s, if any, and then add them back:
'/' + s.strip('/') + '/'
There are several ways to do this, but the fastest (for the computer) is to simply test and augment each end. Using str as the string:
if str[0] != '/':
str = '/' + str
... and repeat for the other end.
Another way is to strip any existing slashes, and then add them to both ends.
If you know that there are no double-slashes within the string, you can add them and then replace doubles (in case you created them at the end):
str = '/' + str + '/'
str.replace('//', '/')
You can strip the string first and then add '/' to beginning and end like this
'/' + <your_string>.strip('/') + '/'
Well the following code solves the purpose of your question. You can simply use an or instead of separate if or elif statements.
def test(x):
if x=="test" or x == "/test" or x=="test/":
print("/",x.strip("/"),"/")
Related
Let's say I have a string like this:
a = a = "\t\t\t\t"
If I print out the count of "\t" in the string, this is the output:
print(a.count("\t")) == output = 4 \
If I wanted to replace "\t" at any given occurrence in that string, how would I do it?
ex:
a.replace("\t", "a") #replacing the (first occurrence?) of "\t?
print(a.count("\t")) == output = 3
However, the "\t" is not getting replaced by "a" and therefore the "\t" count is still 4. Is there a way I can do this; preferably replace any given occurrence of "\t" within the string?
You can use regular expressions. It is another way to replace all the occurencies by specific pattern
try to use expandtabs, such as text = text.expandtabs(tabsize=4)
As Michael Butscher says, str.replace() returns a new string with replacements done. By default, all occurrences are replaced. Tabs are not a special case. This should do it:
a = a.replace("\t", "a")
print(a.count("\t"))
See: https://docs.python.org/3/library/stdtypes.html?highlight=str%20replace#str.replace
Thank you for the responses as they really opened the door to the solution. What I have done is converted a into a list:
a = "\t\t\t\t"
b = a.list()
#print(b):
#['\t', '\t', '\t', '\t']
I can then just use indices to replace what I need b[0] = "a", and then just convert it back into a str when I am done. This suits my purpose, but there are multiple ways of dealing with it like if I wanted to change all the "\t" into a "a" I could do a simple iteration like this:
for x in range(0, len(b)):
if b[x] == "\t":
b[x] = "a"
Of course the replace() function could do the same with it in string format, but at least with this iteration I could add more conditional logic if needed.
how to split the below string after 2nd occurrence of '/' from the end:
/u01/dbms/orcl/product/11.2.0.4/db_home
Expected output is :
/u01/dbms/orcl/product/
Thanks.
Do not use split, use rsplit instead! It's much simpler and faster.
s = '/u01/dbms/orcl/product/11.2.0.4/db_home'
result = s.rsplit('/', 2)[0] + '/'
string = "/u01/dbms/orcl/product/11.2.0.4/db_home"
split_string = string.split('/')
expected_output = "/".join(split_string[:-2]) + "/"
You're also free to change "-2" to minus whatever amount of filenames you need clipped.
If you can parse it as a filepath, I recommend pathlib, try:
from pathlib import Path
p = Path('/u01/dbms/orcl/product/11.2.0.4/db_hom')
p.parent.parent # Returns object containg path /u01/dbms/orc1/product/
input='/u01/dbms/orcl/product/11.2.0.4/db_home'
output = '/'.join(str(word) for word in input.split('/')[:-2])+'/'
How can I convert a hex value "0000.0012.13a4" into "00:00:00:12:13:A4"?
text = '0000.0012.13a4'
text = text.replace('.', '').upper() # a little pre-processing
# chunk into groups of 2 and re-join
out = ':'.join([text[i : i + 2] for i in range(0, len(text), 2)])
print(out)
00:00:00:12:13:A4
import re
old_string = "0000.0012.13a4"
new_string = ':'.join(s for s in re.split(r"(\w{2})", old_string.upper()) if s.isalnum())
print(new_string)
OUTPUT
> python3 test.py
00:00:00:12:13:A4
>
Without modification, this approach can handle some other MAC formats that you might run into like, "00-00-00-12-13-a4"
Try following code
import re
hx = '0000.0012.13a4'.replace('.','')
print(':'.join(re.findall('..', hx)))
Output: 00:00:00:12:13:a4
There is a pretty simple three step solution:
First we strip those pesky periods.
step1 = hexStrBad.replace('.','')
Then, if the formatting is consistent:
step2 = step1[0:2] + ':' + step1[2:4] + ':' + step1[4:6] + ':' + step1[6:8] + ':' + step1[8:10] + ':' + step1[10:12]
step3 = step2.upper()
It's not the prettiest, but it will do what you need!
It's unclear what you're asking exactly, but if all you want is to make a string all uppercase, use .upper()
Try to clarify your question somewhat, because if you're asking about converting some weirdly formatted string into what looks like a MAC address, we need to know that to answer your question.
I have some long strings, fooo, barxxxx\n. How can I output the strings with a single \n at the end? Of course I can do
def padWithReturn(s):
if not s.endswith('\n'):
s+='\n'
return s
padWithReturn('fooo')
but it feels awkward.
I read about How to pad with n characters in Python.
Is there a similar elegant way of doing this, using .format()?
edit : I have over 1000000 lines of text to process. It's a single maya .ma file. will this be slow ?
s.rstrip('\n')+'\n'
or should i use the if else expression, both seem to be too computational intensive ? (haven't tested yet) my hunch tells me if else condition will be faster because it deals with less string ?
A function seems a little overkill here since it can boil down to a single expression:
s if s.endswith('\n') else s + '\n'
Of course, you always can wrap this in a function if you so desire...
Using format, you would do it like this:
if not s.endswith('\n'):
return '{}\n'.format(s)
Simple, just remove the newline, and then tack it on again.
def pad_with_newline(s):
return s.rstrip('\n') + '\n'
Note: If you have multiple newlines on the end of a string, this will remove all of them.
U can try this:
def padWithReturn(a):
if a[-1:] != '\n' : a += '\n'
return a
Using conditional expression:
def padWithReturn(s):
return '{}{}'.format(s, '' if s.endswith('\n') else '\n')
or
def padWithReturn(s):
return '{}{}'.format(s, '\n'[s.endswith('\n'):])
Input
str = 'test1,test2,test3,'
Ouput
str = 'test1,test2,test3'
Requirement to strip the last occurence of ','
Just use rstrip().
result = your_string.rstrip(',')
str = 'test1,test2,test3,'
str[:-1] # 'test1,test2,test3'
The question is very old but tries to give the better answer
str = 'test1,test2,test3,'
It will check the last character, if the last character is a comma it will remove otherwise will return the original string.
result = str[:-1] if str[-1]==',' else str
Though it is little bit over work for something like that. I think this statement will help you.
str = 'test1,test2,test3,'
result = ','.join([s for s in str.split(',') if s]) # 'test1,test2,test3'
If you have to remove the last comma (also as the last character?) you can do this via the function removesuffix()
Here is an example:
>>>'hello,'.removesuffix(',')
'hello'
Actually we have to consider the worst case also.
The worst case is,
str= 'test1,test2,test3, ,,,, '
for above code, please use following code,
result = ','.join([s.strip() for s in str.split(',') if s.strip()!=''])
It will work/remove the prefix 'comma' also. For example,
str= ' , ,test1,test2,test3, ,,,, '