String function to strip the last comma - python

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, ,,,, '

Related

replace a string after substring found in jython/python

I have a string like this
ABC/AAAA DEF/78kkk OBJ/89KKK KLE/67899
and I pass the substring to find and replace after. so If I pass DEF/00012 and the original string
should be replaced as like this
ABC/AAAA DEF/00012 OBJ/89KKK KLE/67899
I have tried with string.replace('DEF', 'DEF/00012')
I would get the output as
ABC/AAAA DEF/00012/78kkk OBJ/89KKK KLE/67899
any suggestions would be highly appreciated.
Thanks
I would do:
txt = 'ABC/AAAA DEF/78kkk OBJ/89KKK KLE/67899'
change = 'DEF'
changeto = 'DEF/00012'
newtxt = ' '.join(changeto if i.startswith(change) else i for i in txt.split(' '))
print(newtxt)
Output:
ABC/AAAA DEF/00012 OBJ/89KKK KLE/67899
I splitted at spaces and changed part beginning with DEF
string.replace('DEF/78kkk', 'DEF/00012')
If you mean by "substring" is that the succeeding characters after "DEF" is not fixed to a specific value, use regular expressions instead.
result = re.sub("DEF/\w+", "DEF/00012", string)
Assuming there really is a blank space after every "substring" you will have to use re:
import re
your_string = re.sub("DEF/*$", "DEF/00012", your_string)

I want to replace a special character with a space

Here is the code i have until now :
dex = tree.xpath('//div[#class="cd-timeline-topic"]/text()')
names = filter(lambda n: n.strip(), dex)
table = str.maketrans(dict.fromkeys('?:,'))
for index, name in enumerate(dex, start = 0):
print('{}.{}'.format(index, name.strip().translate(table)))
The problem is that the output will print also strings with one special character "My name is/Richard". So what i need it's to replace that special character with a space and in the end the printing output will be "My name is Richard". Can anyone help me ?
Thanks!
Your call to dict.fromkeys() does not include the character / in its argument.
If you want to map all the special characters to None, just passing your list of special chars to dict.fromkeys() should be enough. If you want to replace them with a space, you could then iterate over the dict and set the value to for each key.
For example:
special_chars = "?:/"
special_char_dict = dict.fromkeys(special_chars)
for k in special_char_dict:
special_char_dict[k] = " "
You can do this by extending your translation table:
dex = ["My Name is/Richard????::,"]
table = str.maketrans({'?':None,':':None,',':None,'/':' '})
for index, name in enumerate(dex, start = 0):
print('{}.{}'.format(index, name.strip().translate(table)))
OUTPUT
0.My Name is Richard
You want to replace most special characters with None BUT forward slash with a space. You could use a different method to replace forward slashes as the other answers here do, or you could extend your translation table as above, mapping all the other special characters to None and forward slash to space. With this you could have a whole bunch of different replacements happen for different characters.
Alternatively you could use re.sub function following way:
import re
s = 'Te/st st?ri:ng,'
out = re.sub(r'\?|:|,|/',lambda x:' ' if x.group(0)=='/' else '',s)
print(out) #Te st string
Arguments meaning of re.sub is as follows: first one is pattern - it informs re.sub which substring to replace, ? needs to be escaped as otherwise it has special meaning there, | means: or, so re.sub will look for ? or : or , or /. Second argument is function which return character to be used in place of original substring: space for / and empty str for anything else. Third argument is string to be changed.
>>> a = "My name is/Richard"
>>> a.replace('/', ' ')
'My name is Richard'
To replace any character or sequence of characters from the string, you need to use `.replace()' method. So the solution to your answer is:
name.replace("/", " ")
here you can find details

how to remove comma at the end from the below string in python code

input string
str = "(\"Cardinal\", \"Tom B. Erichsen\", \"Skagen 21\",)"
output string should look like:
("Cardinal", "Tom B. Erichsen", "Skagen 21")
The comma at the end should be removed, help me how to do this in python code.
I tried with str.rstrip(",") it dint work.
You can use some regex for example you can replace (.*),([^,]+)$ with \1\2
result = re.sub(r"(.*),([^,]+)$", r"\1\2", yourstring)
here is a regex demo
Check this code
str = str.replace('",)', '")')
you can chain different str.replace()
str.replace(", )",")").replace(",)",")")
That will work for your string
You can do this in following way
str = "(\"Cardinal\", \"Tom B. Erichsen\", \"Skagen 21\",)"
str = str[:len(str)-2] + str[len(str)-1]
You could use the regex module:
import re
s = "INSERT INTO Customers (CustomerName, ContactName, Address, ) VALUES (\"Cardinal\", \"Tom B. Erichsen\", \"Skagen 21\",)"
print re.sub(r',(\s+)*\)', ')', s)

python string, delete character, count from right

I have some strings I created with elements coming from many sources, number of elements will vary each time the program is run; I created a sample string that my program creates now.
I want to count in [:-3] for the following string and delete the last comma:
'{"SEignjExQfumwZRacPNHvq8UcsBjKWPERB":1.00000000,"SCaWymicaunRLAxNSTTRhVxLMAB9PaKBDK":2.80000000,"SGFHTxuRLttUShUjZyFMzs8NgC1JopSUK6":1.20000000,}'
So my string looks like:
'{"SEignjExQfumwZRacPNHvq8UcsBjKWPERB":1.00000000,"SCaWymicaunRLAxNSTTRhVxLMAB9PaKBDK":2.80000000,"SGFHTxuRLttUShUjZyFMzs8NgC1JopSUK6":1.20000000}'
I just cant quite get there, help appreciated.
To remove the third last character from the string you can use:
string[:-3] + string[-2:]
>>> string = "hellothere"
>>> string[:-3] + string[-2:]
'hellothre'
I would use rsplit to split on the right most occurrence of a substring (limiting to two results) and then join them with an empty string
''.join(s.rsplit(',', 2))
a = '{"SEignjExQfumwZRacPNHvq8UcsBjKWPERB":1.00000000,"SCaWymicaunRLAxNSTTRhVxLMAB9PaKBDK":2.80000000,"SGFHTxuRLttUShUjZyFMzs8NgC1JopSUK6":1.20000000,}'
a[:len(a) - 2] + a[len(a) - 1:]
You could obviously use different expressions in the brackets, I just wanted to show that you could use any expressions you wanted.
you can try with rfind to find the last comma
s = '{"SEignjExQfumwZRacPNHvq8UcsBjKWPERB":1.00000000,"SCaWymicaunRLAxNSTTRhVxLMAB9PaKBDK":2.80000000,"SGFHTxuRLttUShUjZyFMzs8NgC1JopSUK6":1.20000000,}'
idx = s.rfind(",")
s[:idx]+s[idx+1:]
you get,
'{"SEignjExQfumwZRacPNHvq8UcsBjKWPERB":1.00000000,"SCaWymicaunRLAxNSTTRhVxLMAB9PaKBDK":2.80000000,"SGFHTxuRLttUShUjZyFMzs8NgC1JopSUK6":1.20000000}'
Using regex:
>>> print re.sub(r ",(?=[^.]*$)", r '', s)
{"SEignjExQfumwZRacPNHvq8UcsBjKWPERB":1.00000000,"SCaWymicaunRLAxNSTTRhVxLMAB9PaKBDK":2.80000000,"SGFHTxuRLttUShUjZyFMzs8NgC1JopSUK6":1.20000000}
This will match a ',' all before a any potential NOT ','. It matches the last ',' right before the end of a string.

Remove the first character of a string

I would like to remove the first character of a string.
For example, my string starts with a : and I want to remove that only. There are several occurrences of : in the string that shouldn't be removed.
I am writing my code in Python.
python 2.x
s = ":dfa:sif:e"
print s[1:]
python 3.x
s = ":dfa:sif:e"
print(s[1:])
both prints
dfa:sif:e
Your problem seems unclear. You say you want to remove "a character from a certain position" then go on to say you want to remove a particular character.
If you only need to remove the first character you would do:
s = ":dfa:sif:e"
fixed = s[1:]
If you want to remove a character at a particular position, you would do:
s = ":dfa:sif:e"
fixed = s[0:pos]+s[pos+1:]
If you need to remove a particular character, say ':', the first time it is encountered in a string then you would do:
s = ":dfa:sif:e"
fixed = ''.join(s.split(':', 1))
Depending on the structure of the string, you can use lstrip:
str = str.lstrip(':')
But this would remove all colons at the beginning, i.e. if you have ::foo, the result would be foo. But this function is helpful if you also have strings that do not start with a colon and you don't want to remove the first character then.
Just do this:
r = "hello"
r = r[1:]
print(r) # ello
deleting a char:
def del_char(string, indexes):
'deletes all the indexes from the string and returns the new one'
return ''.join((char for idx, char in enumerate(string) if idx not in indexes))
it deletes all the chars that are in indexes; you can use it in your case with del_char(your_string, [0])

Categories

Resources