I have this code :
> list=str(raw_input('Enter pipe seprated list [PRIMARY|SECONDARY]:'))
> n_list="^"+list+"$"
> print n_list
when I execute it, it prompts me as :
Enter pipe separated list [PRIMARY|SECONDARY]:PRIMARY
as above if I give PRIMARY its gives me result as :
^PRIMARY$
and if provide the input as PRIMARY|SECONDARY:
Enter pipe seprated list [PRIMARY|SECONDARY]:PRIMARY|SECONDARY
I am getting the output as :
^PRIMARY|SECONDARY$
here I want to get the output as :
^PRIMARY$|^SECONDARY$ if I give the input PRIMARY|SECONDARY. Please help me to achieve this.
Do splitting according to |, add ^ and $ at the start and end of each item. And then join them using |.
>>> s = 'PRIMARY|SECONDARY'
>>> print '|'.join(['^' + i + '$' for i in s.split('|')])
^PRIMARY$|^SECONDARY$
>>> s = 'PRIMARY'
>>> print '|'.join(['^' + i + '$' for i in s.split('|')])
^PRIMARY$
>>> s = 'PRIMARY|SECONDARY|TERTIARY'
>>> print '|'.join(['^' + i + '$' for i in s.split('|')])
^PRIMARY$|^SECONDARY$|^TERTIARY$
>>>
You have to split your string with | (pipe) and concate it with your prefix(^) and postfix($)
l=str(raw_input('Enter pipe seprated list [PRIMARY|SECONDARY]:'))
n_l = "|".join(["^" + l_t + "$" for l_t in l.split('|')])
print n_l
Just for completeness, as an alternative to the split/join solution already proposed, you could also just replace the | with $|^:
>>> s = 'PRIMARY|SECONDARY'
>>> '^' + s.replace('|', '$|^') + '$'
'^PRIMARY$|^SECONDARY$'
However, since in this solution you have to write both ^ and $ twice, I would still prefer the split/join way.
Another solution: Instead of using the regex '^PRIMARY$|^SECONDARY$', you could also use '^(PRIMARY|SECONDARY)$'. The behaviour should be the same.
Related
I am doing a program that changes a number in base 10 to base 7, so i did this :
num = int(raw_input(""))
mod = int(0)
list = []
while num> 0:
mod = num%7
num = num/7
list.append(mod)
list.reverse()
for i in range (0,len(list)):
print list[i],
But if the number is 210 it prints 4 2 0 how do i get rid of the spaces
You can use join with list comprehension:
>>> l=range(5)
>>> print l
[0, 1, 2, 3, 4]
>>> ''.join(str(i) for i in l)
'01234'
Also, don't use list as a variable name since it is a built-in function.
In python 3 you can do like this :
print(*range(1,int(input())+1), sep='')
Your output will be like this if input = 4 :
1234
Convert the list to a string, and replace the white spaces.
strings = ['hello', 'world']
print strings
>>>['hello', 'world']
print str(strings).replace(" ", "")
>>>['hello','world']
Take a look at sys.stdout. It's a file object, wrapping standard output. As every file it has write method, which takes string, and puts it directly to STDOUT. It also doesn't alter nor add any characters on it's own, so it's handy when you need to fully control your output.
>>> import sys
>>> for n in range(8):
... sys.stdout.write(str(n))
01234567>>>
Note two things
you have to pass string to the function.
you don't get newline after printing.
Also, it's handy to know that the construct you used:
for i in range (0,len(list)):
print list[i],
is equivalent to (frankly a bit more efficient):
for i in list:
print i,
Doing the following worked for me in Python3
print(*list,sep='')
You can use below code snippet for python3
print(*list(range(1, n + 1)), sep='')
* will remove initial and end character like [{}]
sep = '' will remove the spaces between item.
Use list_comprehension.
num= int(raw_input(""))
mod=int(0)
list =[]
while num> 0:
mod=num%7
num=num/7
list.append(mod)
list.reverse()
print ''.join([str(list[i]) for i in range (0,len(list))])
The print() function has an argument to specify the end character which by default is '\n'. Specifying the end character as '' and printing using a loop will do what you are looking for:
n_list = [1,2,3,4,5]
for i in n_list:
print(i, end='')
s = "jay"
list = [ i for i in s ]
It you print list you will get:
['j','a','y']
new_s = "".join(list)
If you print new_s:
"jay"
I want each word in the sentence to be changed on asterisk, I'm trying to use one line code here, but I have no idea how do I get the asterisk for each word
from string import join, split
def asterisk(s):
return join(map(lambda x: x[:0], split(s)), " * ")
print asterisk("lame af sentence")
The output:
* *
As you could notice it changes only 2 words after split(). I have tried to use lambda function to assign x = " * " to the asterisk, but it doesn't support that way.
So, any help would be appreciated, thanks in advance!
Your code puts an asterisk between every join. There are 2 join between words, so two asterisks.
I think you want
join(map(lambda x: "*", split(s)), " ")
You can use str.split and str.join here:
>>> strs = "lame af sentence"
>>> ' '.join('*'*len(strs.split()))
'* * *'
Here str.split splits the string at white-spaces and returns a list:
>>> spl = strs.split()
>>> spl
['lame', 'af', 'sentence']
Now using the length of this list and str.join we can do:
>>> ' '.join("*"*len(spl))
'* * *'
If you want to preserve the white-spaces, regex may help:
>>> import re
>>> strs = "lame af sentence"
>>> re.sub(r'\S+', '*', strs)
'* * *'
Here is another one you could use:
def asterisk(s):
return ' '.join(['*' for word in s.split()])
print asterisk("lame af sentence")
Follow these steps:
Count how many words you have: words=len(s.split())
Add one * followed by a space per word: for i in range(words): out+='* '
Cut last space: out=out[:-1]
In one line: return '* '.join([i for i in range(len(s.split()))])[:-1]
If I have a series of python strings that I'm working with that will always take the form of
initialword_content
and I want to strip out the initialword portion, which will always be the same number of characters, and then I want to turn all instances of _ into spaces -- since content may have some underscores in it -- what's the easiest way to do that?
strs = "initialword_content"
strs = strs[12:].replace("_", " ")
print strs
Due to the initialword always has same number of character, so you can just get the suffix of the string. And use string.replace to replace all "_" into spaces.
First, split the string once (with the parameter 1 to split) to get two parts: the throw-away 'initialword' and the rest, where you replace all underscores with spaces.
s = 'initialword_content'
a, b = s.split('_', 1)
b = b.replace('_', ' ')
# b == 'content'
s = 'initialword_content_with_more_words'
a, b = s.split('_', 1)
b = b.replace('_', ' ')
# b == 'content with more words'
This can be done with a single command:
s.split('_', 1)[1].replace('_', ' ')
another way:
' '.join(s.split('_')[1:])
or, if the length of "initialword" is always the same (and you don't have to calculate it each time), take the #JunHu's solution.
I used slicing and the replace() function. replace() simply... replaces!
string = 'initialword_content'
content = string[12:] # You mentioned that intialword will always be the same length, so I used slicing.
content = content.replace('_', ' ')
For example:
>>> string = 'elephantone_con_ten_t' # elephantone was the first thing I thought of xD
>>> content = string[12:]
>>> content
... con_ten_t
>>> content = content.replace('_', ' ')
>>> content
... con ten t
However, if you also want to reference "elephantone" somewhere else, do this:
>>> string = 'elephantone_con_ten_t'
>>> l = string.split('_', 1) # This will only strip the string ONCE from the left.
>>> l[0]
... 'elephantone'
>>> l[1].replace('_', ' ')
... 'con ten t'
I am new and trying to find a way to insert a number of L's at the beginning and end of a string. So if I have a string which says
"where did I put my cupcake this morning"
And I want to insert 1 L at the start and 2 L's at the end, so it looks like: "Lwhere did I put my cupcake this morningLL" How do I do this. thank you
Strings are immutable so you can't insert characters into an existing string. You have to create a new string. You can use string concatenation to do what you want:
yourstring = "L" + yourstring + "LL"
Note that you can also create a string with n Ls by using multiplication:
m = 1
n = 2
yourstring = ("L" * m) + yourstring + ("L" * n)
For completeness along with the other answers:
yourstring = "L%sLL" % yourstring
Or, more forward compatible with Python 3.x:
yourstring = "L{0}LL".format(yourstring)
You can also use join:
yourstring = ''.join(('L','yourstring','LL'))
Result:
>>> yourstring
'LyourstringLL'
If you want to insert other string somewhere else in existing string, you may use selection method below.
Calling character on second position:
>>> s = "0123456789"
>>> s[2]
'2'
Calling range with start and end position:
>>> s[4:6]
'45'
Calling part of a string before that position:
>>> s[:6]
'012345'
Calling part of a string after that position:
>>> s[4:]
'456789'
Inserting your string in 5th position.
>>> s = s[:5] + "L" + s[5:]
>>> s
'01234L56789'
Also s is equivalent to s[:].
With your question you can use all your string, i.e.
>>> s = "L" + s + "LL"
or if "L" is a some other string (for example I call it as l), then you may use that code:
>>> s = l + s + (l * 2)
Adding to C2H5OH's answer, in Python 3.6+ you can use format strings to make it a bit cleaner:
s = "something about cupcakes"
print(f"L{s}LL")
Let's say we have a string called yourstring:
for x in range(0, [howmanytimes you want it at the beginning]):
yourstring = "L" + yourstring
for x in range(0, [howmanytimes you want it at the end]):
yourstring += "L"
you can use f strings for this
foo = "where did I put my cupcake this morning"
bar = 'L'
foobar = f'{bar*10}{foo}'
print(foobar)
you can replace 10 by how many times you want to put L's in your string
for end also you can do the same
foo = "where did I put my cupcake this morning"
bar = 'L'
foobar = f'{bar*10}{foo}{bar*10}'
print(foobar)
I have a string s with nested brackets: s = "AX(p>q)&E((-p)Ur)"
I want to remove all characters between all pairs of brackets and store in a new string like this: new_string = AX&E
i tried doing this:
p = re.compile("\(.*?\)", re.DOTALL)
new_string = p.sub("", s)
It gives output: AX&EUr)
Is there any way to correct this, rather than iterating each element in the string?
Another simple option is removing the innermost parentheses at every stage, until there are no more parentheses:
p = re.compile("\([^()]*\)")
count = 1
while count:
s, count = p.subn("", s)
Working example: http://ideone.com/WicDK
You can just use string manipulation without regular expression
>>> s = "AX(p>q)&E(qUr)"
>>> [ i.split("(")[0] for i in s.split(")") ]
['AX', '&E', '']
I leave it to you to join the strings up.
>>> import re
>>> s = "AX(p>q)&E(qUr)"
>>> re.compile("""\([^\)]*\)""").sub('', s)
'AX&E'
Yeah, it should be:
>>> import re
>>> s = "AX(p>q)&E(qUr)"
>>> p = re.compile("\(.*?\)", re.DOTALL)
>>> new_string = p.sub("", s)
>>> new_string
'AX&E'
Nested brackets (or tags, ...) are something that are not possible to handle in a general way using regex. See http://www.amazon.de/Mastering-Regular-Expressions-Jeffrey-Friedl/dp/0596528124/ref=sr_1_1?ie=UTF8&s=gateway&qid=1304230523&sr=8-1-spell for details why. You would need a real parser.
It's possible to construct a regex which can handle two levels of nesting, but they are already ugly, three levels will already be quite long. And you don't want to think about four levels. ;-)
You can use PyParsing to parse the string:
from pyparsing import nestedExpr
import sys
s = "AX(p>q)&E((-p)Ur)"
expr = nestedExpr('(', ')')
result = expr.parseString('(' + s + ')').asList()[0]
s = ''.join(filter(lambda x: isinstance(x, str), result))
print(s)
Most code is from: How can a recursive regexp be implemented in python?
You could use re.subn():
import re
s = 'AX(p>q)&E((-p)Ur)'
while True:
s, n = re.subn(r'\([^)(]*\)', '', s)
if n == 0:
break
print(s)
Output
AX&E
this is just how you do it:
# strings
# double and single quotes use in Python
"hey there! welcome to CIP"
'hey there! welcome to CIP'
"you'll understand python"
'i said, "python is awesome!"'
'i can\'t live without python'
# use of 'r' before string
print(r"\new code", "\n")
first = "code in"
last = "python"
first + last #concatenation
# slicing of strings
user = "code in python!"
print(user)
print(user[5]) # print an element
print(user[-3]) # print an element from rear end
print(user[2:6]) # slicing the string
print(user[:6])
print(user[2:])
print(len(user)) # length of the string
print(user.upper()) # convert to uppercase
print(user.lstrip())
print(user.rstrip())
print(max(user)) # max alphabet from user string
print(min(user)) # min alphabet from user string
print(user.join([1,2,3,4]))
input()