python, string methods [duplicate] - python

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Pythonic way to insert every 2 elements in a string
I'll be happy if someone can help with python code))
How can I put the space into a string
for example,
If there is the string 'akhfkahgdsds'
I would like to turn it into 'ak hf ka hg ds ds'

>>> s = 'akhfkahgdsds'
>>> range(0, len(s), 2) # gives you the start indexes of your substrings
[0, 2, 4, 6, 8, 10]
>>> [s[i:i+2] for i in range(0, len(s), 2)] # gives you the substrings
['ak', 'hf', 'ka', 'hg', 'ds', 'ds']
>>> ' '.join(s[i:i+2] for i in range(0, len(s), 2)) # join the substrings with spaces between them
'ak hf ka hg ds ds'

def isection(itr, size):
while itr:
yield itr[:size]
itr = itr[size:]
' '.join(isection('akhfkahgdsds', 2))

I don't really think this is the way to go here, but I think this answer is kind of fun anyway. If the length of the string is always even, you can play neat tricks with iter -- if it's odd, the last character will be truncated:
s = '11223344'
i_s = iter(s)
' '.join(x+next(i_s) for x in i_s)
Of course, you can always pad it:
i_s = iter(s+len(s)%2*' ')

you can try this simple code:
try:
for i in range(0,len(s)+1,2):
print s[i]+s[i+1],
except IndexError:
pass

Related

I am able to parse the log file but not getting output in correct format in python [duplicate]

How do I concatenate a list of strings into a single string?
For example, given ['this', 'is', 'a', 'sentence'], how do I get "this-is-a-sentence"?
For handling a few strings in separate variables, see How do I append one string to another in Python?.
For the opposite process - creating a list from a string - see How do I split a string into a list of characters? or How do I split a string into a list of words? as appropriate.
Use str.join:
>>> words = ['this', 'is', 'a', 'sentence']
>>> '-'.join(words)
'this-is-a-sentence'
>>> ' '.join(words)
'this is a sentence'
A more generic way (covering also lists of numbers) to convert a list to a string would be:
>>> my_lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> my_lst_str = ''.join(map(str, my_lst))
>>> print(my_lst_str)
12345678910
It's very useful for beginners to know
why join is a string method.
It's very strange at the beginning, but very useful after this.
The result of join is always a string, but the object to be joined can be of many types (generators, list, tuples, etc).
.join is faster because it allocates memory only once. Better than classical concatenation (see, extended explanation).
Once you learn it, it's very comfortable and you can do tricks like this to add parentheses.
>>> ",".join("12345").join(("(",")"))
Out:
'(1,2,3,4,5)'
>>> list = ["(",")"]
>>> ",".join("12345").join(list)
Out:
'(1,2,3,4,5)'
Edit from the future: Please don't use the answer below. This function was removed in Python 3 and Python 2 is dead. Even if you are still using Python 2 you should write Python 3 ready code to make the inevitable upgrade easier.
Although #Burhan Khalid's answer is good, I think it's more understandable like this:
from str import join
sentence = ['this','is','a','sentence']
join(sentence, "-")
The second argument to join() is optional and defaults to " ".
list_abc = ['aaa', 'bbb', 'ccc']
string = ''.join(list_abc)
print(string)
>>> aaabbbccc
string = ','.join(list_abc)
print(string)
>>> aaa,bbb,ccc
string = '-'.join(list_abc)
print(string)
>>> aaa-bbb-ccc
string = '\n'.join(list_abc)
print(string)
>>> aaa
>>> bbb
>>> ccc
We can also use Python's reduce function:
from functools import reduce
sentence = ['this','is','a','sentence']
out_str = str(reduce(lambda x,y: x+"-"+y, sentence))
print(out_str)
We can specify how we join the string. Instead of '-', we can use ' ':
sentence = ['this','is','a','sentence']
s=(" ".join(sentence))
print(s)
If you have a mixed content list and want to stringify it, here is one way:
Consider this list:
>>> aa
[None, 10, 'hello']
Convert it to string:
>>> st = ', '.join(map(str, map(lambda x: f'"{x}"' if isinstance(x, str) else x, aa)))
>>> st = '[' + st + ']'
>>> st
'[None, 10, "hello"]'
If required, convert back to the list:
>>> ast.literal_eval(st)
[None, 10, 'hello']
If you want to generate a string of strings separated by commas in final result, you can use something like this:
sentence = ['this','is','a','sentence']
sentences_strings = "'" + "','".join(sentence) + "'"
print (sentences_strings) # you will get "'this','is','a','sentence'"
def eggs(someParameter):
del spam[3]
someParameter.insert(3, ' and cats.')
spam = ['apples', 'bananas', 'tofu', 'cats']
eggs(spam)
spam =(','.join(spam))
print(spam)
Without .join() method you can use this method:
my_list=["this","is","a","sentence"]
concenated_string=""
for string in range(len(my_list)):
if string == len(my_list)-1:
concenated_string+=my_list[string]
else:
concenated_string+=f'{my_list[string]}-'
print([concenated_string])
>>> ['this-is-a-sentence']
So, range based for loop in this example , when the python reach the last word of your list, it should'nt add "-" to your concenated_string. If its not last word of your string always append "-" string to your concenated_string variable.

How to split python string every nth-1 + nth char [duplicate]

This question already has answers here:
How do I split a list into equally-sized chunks?
(66 answers)
Closed 6 years ago.
For example, suppose we have a string:
'abcdefg'
And we need to get a list like this:
['ab', 'bc', 'cd', 'de', 'ef', 'fg']
we should not use any kind of library
Here is my solution:
def str_split(s):
s = iter(s)
ch1=''
ch2=''
chars_list=[]
while True:
try:
ch1 = ch2 or next(s)
ch2 = next(s)
chars_list.append(ch1 + ch2)
except:
break
return chars_list
I wonder is there a better solution? Maybe it is possible to use list comprehension like here?
You can simply use zip() and a list comprehension:
chars_list = [ch1 + ch2 for ch1, ch2 in zip(s, s[1:])]
More generally, if you need a solution for any n:
n = 3
chars_list = [s[i:i+n] for i in range(0, len(s) - n + 1, n - 1)]
# ['abc', 'cde', 'efg']
You could try this (hacky) solution:
def str_split(s):
return [s[start:end] for start, end in enumerate(range(2, len(s)+1))]
Delgan's zipping solution seems more elegant though :)

Extraction of 2 or more digit number into a list from string like 12+13

I'm trying to extract numbers from a string like "12+13".
When I extract only the numbers from it into a list it becomes [1,2,1,3]
actually I want the list to take the numbers as [12,13] and 12,13 should be integers also.
I have tried my level best to solve this,the following is the code
but it still has a disadvantage .
I am forced to put a space at the end of the string...for it's correct functioning.
My Code
def extract(string1):
l=len(string1)
pos=0
num=[]
continuity=0
for i in range(l):
if string[i].isdigit()==True:
continuity+=1
else:
num=num+ [int(string[pos:continuity])]
continuity+=1
pos=continuity
return num
string="1+134-15 "#added a spaces at the end of the string
num1=[]
num1=extract(string)
print num1
This will work perfectly with your situation (and with all operators, not just +):
>>> import re
>>> equation = "12+13"
>>> tmp = re.findall('\\b\\d+\\b', equation)
>>> [int(i) for i in tmp]
[12, 13]
But if you format your string to be with spaces between operators (which I think is the correct way to go, and still supports all operators, with a space) then you can do this without even using regex like this:
>>> equation = "12 + 13"
>>> [int(s) for s in equation.split() if s.isdigit()]
[12, 13]
Side note: If your only operator is the + one, you can avoid regex by doing:
>>> equation = "12+13"
>>> [int(s) for s in equation.split("+") if s.isdigit()]
[12, 13]
The other answer is great (as of now), but I want to provide you with a detailed explanation. What you are trying to do is split the string on the "+" symbol. In python, this can be done with str.split("+").
When that translates into your code, it turns out like this.
ourStr = "12+13"
ourStr = ourStr.split("+")
But, don't you want to convert those to integers? In python, we can use list comprehension with int() to achieve this result.
To convert the entire array to ints, we can use. This pretty much loops over each index, and converts the string to an integer.
str = [int(s) for s in ourStr]
Combining this together, we get
ourStr = "12+13"
ourStr = ourStr.split("+")
ourStr = [int(s) for s in ourStr]
But lets say their might be other unknown symbols in the array. Like #Idos used, it is probably a good idea to check to make sure it is a number before putting it in the array.
We can further refine the code to:
ourStr = "12+13"
ourStr = ourStr.split("+")
ourStr = [int(s) for s in ourStr if s.isdigit()]
This can be solved with just list comprehension or built-in methods, no need for regex:
s = '12+13+14+15+16'
l = [int(x) for x in s.split('+')]
l = map(int, s.split('+'))
l = list(map(int, s.split('+'))) #If Python3
[12, 13, 14, 15, 16]
If you are not sure whether there are any non-digit strings, then just add condition to the list comprehension:
l = [int(x) for x in s.split('+') if x.isdigit()]
l = map(lambda s:int(s) if s.isdigit() else None, s.split('+'))
l = list(map(lambda s:int(s) if s.isdigit() else None, s.split('+'))) #If python3
Now consider a case where you could have something like:
s = '12 + 13 + 14+15+16'
l = [int(x.strip()) for x in s.split('+') if x.strip().isdigit()]#had to strip x for any whitespace
l = (map(lambda s:int(s.strip()) if s.strip().isdigit() else None, s.split('+'))
l = list(map(lambda s:int(s.strip()) if s.strip().isdigit() else None, s.split('+'))) #Python3
[12, 13, 14, 15, 16]
Or:
l = [int(x) for x in map(str.strip,s.split('+')) if x.isdigit()]
l = map(lambda y:int(y) if y.isdigit() else None, map(str.strip,s.split('+')))
l = list(map(lambda y:int(y) if y.isdigit() else None, map(str.strip,s.split('+')))) #Python3
You can just use Regular Expressions, and this becomes very easy:
>>> s = "12+13"
>>> import re
>>> re.findall(r'\d+',s)
['12', '13']
basically, \d matches any digit and + means 1 or more. So re.findall(r'\d+',s) is looking for any part of the string that is 1 or more digits in a row and returns each instance it finds!
in order to turn them to integers, as many people have said, you can just use a list comprehension after you get the result:
result = ['12', '13']
int_list = [int(x) for x in result]
python regex documentation
I have made a function which extracts number from a string.
def extract(string1):
string1=string1+" "
#added a spaces at the end of the string so that last number is also extracted
l=len(string1)
pos=0
num=[]
continuity=0
for i in range(l):
if string1[i].isdigit()==True:
continuity+=1
else:
if pos!=continuity:
''' This condition prevents consecutive execution
of else part'''
num=num+ [int(string1[pos:continuity])]
continuity+=1
pos=continuity
return num
string="ab73t9+-*/182"
num1=[]
num1=extract(string)
print num1

Python - How to add space on each 3 characters?

I need to add a space on each 3 characters of a python string but don't have many clues on how to do it.
The string:
345674655
The output that I need:
345 674 655
Any clues on how to achieve this?
Best Regards,
You just need a way to iterate over your string in chunks of 3.
>>> a = '345674655'
>>> [a[i:i+3] for i in range(0, len(a), 3)]
['345', '674', '655']
Then ' '.join the result.
>>> ' '.join([a[i:i+3] for i in range(0, len(a), 3)])
'345 674 655'
Note that:
>>> [''.join(x) for x in zip(*[iter(a)]*3)]
['345', '674', '655']
also works for partitioning the string. This will work for arbitrary iterables (not just strings), but truncates the string where the length isn't divisible by 3. To recover the behavior of the original, you can use itertools.izip_longest (itertools.zip_longest in py3k):
>>> import itertools
>>> [''.join(x) for x in itertools.izip_longest(*[iter(a)]*3, fillvalue=' ')]
['345', '674', '655']
Of course, you pay a little in terms of easy reading for the improved generalization in these latter answers ...
Best Function based on #mgilson's answer
def litering_by_three(a):
return ' '.join([a[i:i + 3] for i in range(0, len(a), 3)])
# replace (↑) with you character like ","
output example:
>>> x="500000"
>>> print(litering_by_three(x))
'500 000'
>>>
or for , example:
>>> def litering_by_three(a):
>>> return ','.join([a[i:i + 3] for i in range(0, len(a), 3)])
>>> # replace (↑) with you character like ","
>>> print(litering_by_three(x))
'500,000'
>>>
a one-line solution will be
" ".join(splitAt(x,3))
however, Python is missing a splitAt() function, so define yourself one
def splitAt(w,n):
for i in range(0,len(w),n):
yield w[i:i+n]
How about reversing the string to jump by 3 starting from the units, then reversing again. The goal is to obtain "12 345".
n="12345"
" ".join([n[::-1][i:i+3] for i in range(0, len(n), 3)])[::-1]
Join with '-' the concatenated of the first, second and third characters of each 3 characters:
' '.join(a+b+c for a,b,c in zip(x[::3], x[1::3], x[2::3]))
Be sure string length is dividable by 3

How to concatenate (join) items in a list to a single string

How do I concatenate a list of strings into a single string?
For example, given ['this', 'is', 'a', 'sentence'], how do I get "this-is-a-sentence"?
For handling a few strings in separate variables, see How do I append one string to another in Python?.
For the opposite process - creating a list from a string - see How do I split a string into a list of characters? or How do I split a string into a list of words? as appropriate.
Use str.join:
>>> words = ['this', 'is', 'a', 'sentence']
>>> '-'.join(words)
'this-is-a-sentence'
>>> ' '.join(words)
'this is a sentence'
A more generic way (covering also lists of numbers) to convert a list to a string would be:
>>> my_lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> my_lst_str = ''.join(map(str, my_lst))
>>> print(my_lst_str)
12345678910
It's very useful for beginners to know
why join is a string method.
It's very strange at the beginning, but very useful after this.
The result of join is always a string, but the object to be joined can be of many types (generators, list, tuples, etc).
.join is faster because it allocates memory only once. Better than classical concatenation (see, extended explanation).
Once you learn it, it's very comfortable and you can do tricks like this to add parentheses.
>>> ",".join("12345").join(("(",")"))
Out:
'(1,2,3,4,5)'
>>> list = ["(",")"]
>>> ",".join("12345").join(list)
Out:
'(1,2,3,4,5)'
Edit from the future: Please don't use the answer below. This function was removed in Python 3 and Python 2 is dead. Even if you are still using Python 2 you should write Python 3 ready code to make the inevitable upgrade easier.
Although #Burhan Khalid's answer is good, I think it's more understandable like this:
from str import join
sentence = ['this','is','a','sentence']
join(sentence, "-")
The second argument to join() is optional and defaults to " ".
list_abc = ['aaa', 'bbb', 'ccc']
string = ''.join(list_abc)
print(string)
>>> aaabbbccc
string = ','.join(list_abc)
print(string)
>>> aaa,bbb,ccc
string = '-'.join(list_abc)
print(string)
>>> aaa-bbb-ccc
string = '\n'.join(list_abc)
print(string)
>>> aaa
>>> bbb
>>> ccc
We can also use Python's reduce function:
from functools import reduce
sentence = ['this','is','a','sentence']
out_str = str(reduce(lambda x,y: x+"-"+y, sentence))
print(out_str)
We can specify how we join the string. Instead of '-', we can use ' ':
sentence = ['this','is','a','sentence']
s=(" ".join(sentence))
print(s)
If you have a mixed content list and want to stringify it, here is one way:
Consider this list:
>>> aa
[None, 10, 'hello']
Convert it to string:
>>> st = ', '.join(map(str, map(lambda x: f'"{x}"' if isinstance(x, str) else x, aa)))
>>> st = '[' + st + ']'
>>> st
'[None, 10, "hello"]'
If required, convert back to the list:
>>> ast.literal_eval(st)
[None, 10, 'hello']
If you want to generate a string of strings separated by commas in final result, you can use something like this:
sentence = ['this','is','a','sentence']
sentences_strings = "'" + "','".join(sentence) + "'"
print (sentences_strings) # you will get "'this','is','a','sentence'"
def eggs(someParameter):
del spam[3]
someParameter.insert(3, ' and cats.')
spam = ['apples', 'bananas', 'tofu', 'cats']
eggs(spam)
spam =(','.join(spam))
print(spam)
Without .join() method you can use this method:
my_list=["this","is","a","sentence"]
concenated_string=""
for string in range(len(my_list)):
if string == len(my_list)-1:
concenated_string+=my_list[string]
else:
concenated_string+=f'{my_list[string]}-'
print([concenated_string])
>>> ['this-is-a-sentence']
So, range based for loop in this example , when the python reach the last word of your list, it should'nt add "-" to your concenated_string. If its not last word of your string always append "-" string to your concenated_string variable.

Categories

Resources