I just can not figure it out how to easily do it in python:
myArray = ["this ","is ","a ","test.","this ","is ","another ","test."]
now I want the output to be
print(myArray[0:3]) -> "this is a test"
print(myArray[4:7]) -> "this is another test"
Is there a feature in python that allows this without iterating over the whole array within a for word in myArray ...
What I get is an index in a loop which only tells me up to which word I should "print" it.
I prefer a python "exclusive" variant, which is short and simple, best case a one liner and it should need as less memory as possible (fast even for thousands of attempts)
You can try join(), I hope this is the solution you are looking for
myArray = ["this ","is ","a ","test.","this ","is ","another ","test."]
print(' '.join(myArray[:4]))
print(' '.join(myArray[4:]))
It seems like what you actually want is to join together some sublist in your list of words.
>>> myArray = ["this ","is ","a ","test.","this ","is ","another ","test."]
>>> print(''.join(myArray[0:4]))
this is a test.
>>> print(''.join(myArray[4:8]))
this is another test.
I guess you have to make it myArray[0:4] and join function...
print("".join(myArray[0:4]))
print("".join(myArray[4:8]))
You need to use the string method join(). This method applies to a separator. For instance:
"".join(myArray[0:4])
Will output:
'this is a test.'
You were close.
For python 2.7:
print " ".join(test[0:3])
For python 3.x:
print(*test[0:3])
As the other guys have said, you can always use join:
//generate 10 letters
myArray = [chr(letter) for letter in range(97,107)]
//return letters from 0 to 5
"".join(myArray)[0:5]
However, I don't understand why you can't use this format
print[0:5]
In terms of efficiency, the latter option is better, and it is just as pythonic as the former.
When you 'join' the array, you are implicitly interating over it, and when you finally display the necessary elements, you are iterating again.
just use the join()
first="".join(myArray[0:3])
second="".join(myArray[4:7])
as friends have told you can use join in python:
print("".join(myArray[x:y]))
which puts what you call join on it (here "") between elements as seperator and returns as string.
one good way is just remove ending space from your array and do like this:
print(" ".join(myArray[x:y]))
print(''.join(myArray[:4])) -> "this is a test"
print(''.join(myArray[4:])) -> "this is another test"
Related
I am just wondering if there is such possibility to hide somehow part of string in python. I am not talking about slicing. I am talking about situation where I have "1somestring," while printing I obtain "somestring". 1 before somestring should be visible for python but not displayable. Or It could be nice to have some kind of indicator glued to string. What I want to achieve is custom sorting. I have list of strings and I want to sort them by addition of digits in front of them. Sorting will proceed basing on digits thus behind digits I can insert whatever I want, but I don’t want to have digits visible. Thanks for answers in advance.
You could store them in a list, with each entry consisting of a tuple indicating order (low to high), then the string. The default sorting on this list would place them in order.
words = [(1,"blah"), (3,"wibble"), (2,"splop")]
words.sort()
print(words)
[(1, 'blah'), (2, 'splop'), (3, 'wibble')]
print(" ".join(word[1] for word in words))
blah splop wibble
I think something simple like a situation where you have a list of things like:
['1something', '2more', '3another']
is to modify each element using an empty substitution, then print:
import re
for item in list:
charonly = re.sub('[0-9]','', item)
print charonly
This does not require "hiding" information in your string. It simply requires combining them with your other information (the numbers) at sorting time, and that can be done in many ways. Here's one:
# my strings, and the order I'd like them to have
my_strings = ["how", "there", "hello", "you", "are"]
my_ordering = [2, 1, 0, 3, 4]
# sort them
sorted_strings = [x for _, x in sorted(zip(my_ordering, my_strings))]
print(sorted_strings)
You can define a print function other than the built-in one. So this might not be exactly seek, what you want to do is better explained in the comments. But this is also a way.
def print2(string):
print "".join(letter for letter in string if letter.isalpha())
In you script, if you restrict the usage of the print function and only use the one you defined. It could be a solution.
I will ask to the question in the title:
Let's say that our string is:
ceva="123Password"
If you want to hider first 2:
ceva=ceva[2:]
ceva will be '3Password'
Now let's play with list of strings:
lista=["abc","ghi","def"]
for _,x in enumerate(sorted(lista)):
print(str(_)+x)
0abc
1def
2ghi
or
lista=["abc","ghi","def"]
for _,x in enumerate(sorted(lista)):
lista[_]=str(_)+x
>>> lista
['0abc', '1def', '2ghi']
I have various strings
123_dog
2_fish
56_cat
45_cat_fish
There is always one number. Always a '_' after the number.
I need to remove the number and the underscore. I can use regex, but I wonder if there is some pythonic way that uses builtin methods?
(I'm an experienced coder - but new to Python.)
Assuming that there is always an underscore after the number, and that there is always exactly a single number, you can do this:
s = '45_cat_fish'
print s.split('_', 1)[1]
# >>> cat_fish
The argument to split specifies the maximum number of splits to perform.
Using split and join:
>>> a="45_cat_fish"
>>> '_'.join(a.split('_')[1:])
'cat_fish'
Edit: split can take a maxsplit argument (see YS-L answer), so '_'.join is unnecessary, a.split('_',1)[1]…
Using find
>>> a[a.find('_')+1:]
'cat_fish'
Another way is:
s = "45_cat_fish"
print ''.join(c for c in s if c.isalpha() or c == '_')[1:]
gives cat_fish
Is there any "pythonic way" to tell python to loop in a string (or list) starting from the last item and ending with the first one?
For example the word Hans i want python to read or sort it as snaH
Next, how can i tell pyhon the following: now from the string you resulted , search for 'a' find it ok , if you find 'n' follows 'a' , put '.' after 'n' and then print the original order of letters
The clearest and most pythonic way to do this is to used the reversed() builtin.
wrong_way = [1, 2, 3, 4]
for item in reversed(wrong_way):
print(item)
Which gives:
4
3
2
1
This is the best solution as not only will it generate a reversed iterator naturally, but it can also call the dedicated __reversed__() method if it exists, allowing for a more efficient reversal in some objects.
You can use wrong_way[::-1] to reverse a list, but this is a lot less readable in code, and potentially less efficient. It does, however, show the power of list slicing.
Note that reversed() provide iterators, so if you want to do this with a string, you will need to convert your result back to a string, which is fortunately easy, as you just do:
"".join(iterator)
e.g:
"".join(reversed(word))
The str.join() method takes an iterator and joins every element into a string, using the calling string as the separator, so here we use the empty string to place them back-to-back.
How about this?
>>> s = "Hans"
>>> for c in s[::-1]:
print c
s
n
a
H
Alternatively, if you want a new string that's the reverse of the first, try this:
>>> "".join(reversed("Hans"))
'snaH'
Sure, just use list_name[::-1]. e.g.
>>> l = ['one', 'two', 'three']
>>> for i in l[::-1]:
... print i
...
three
two
one
I'm relatively new to Python and it's libraries and I was wondering how I might create a string array with a preset size. It's easy in java but I was wondering how I might do this in python.
So far all I can think of is
strs = ['']*size
And some how when I try to call string methods on it, the debugger gives me an error X operation does not exist in object tuple.
And if it was in java this is what I would want to do.
String[] ar = new String[size];
Arrays.fill(ar,"");
Please help.
Error code
strs[sum-1] = strs[sum-1].strip('\(\)')
AttributeError: 'tuple' object has no attribute 'strip'
Question: How might I do what I can normally do in Java in Python while still keeping the code clean.
In python, you wouldn't normally do what you are trying to do. But, the below code will do it:
strs = ["" for x in range(size)]
In Python, the tendency is usually that one would use a non-fixed size list (that is to say items can be appended/removed to it dynamically). If you followed this, there would be no need to allocate a fixed-size collection ahead of time and fill it in with empty values. Rather, as you get or create strings, you simply add them to the list. When it comes time to remove values, you simply remove the appropriate value from the string. I would imagine you can probably use this technique for this. For example (in Python 2.x syntax):
>>> temp_list = []
>>> print temp_list
[]
>>>
>>> temp_list.append("one")
>>> temp_list.append("two")
>>> print temp_list
['one', 'two']
>>>
>>> temp_list.append("three")
>>> print temp_list
['one', 'two', 'three']
>>>
Of course, some situations might call for something more specific. In your case, a good idea may be to use a deque. Check out the post here: Python, forcing a list to a fixed size. With this, you can create a deque which has a fixed size. If a new value is appended to the end, the first element (head of the deque) is removed and the new item is appended onto the deque. This may work for what you need, but I don't believe this is considered the "norm" for Python.
The simple answer is, "You don't." At the point where you need something to be of fixed length, you're either stuck on old habits or writing for a very specific problem with its own unique set of constraints.
The best and most convenient method for creating a string array in python is with the help of NumPy library.
Example:
import numpy as np
arr = np.chararray((rows, columns))
This will create an array having all the entries as empty strings. You can then initialize the array using either indexing or slicing.
Are you trying to do something like this?
>>> strs = [s.strip('\(\)') for s in ['some\\', '(list)', 'of', 'strings']]
>>> strs
['some', 'list', 'of', 'strings']
But what is a reason to use fixed size? There is no actual need in python to use fixed size arrays(lists) so you always have ability to increase it's size using append, extend or decrease using pop, or at least you can use slicing.
x = ['' for x in xrange(10)]
strlist =[{}]*10
strlist[0] = set()
strlist[0].add("Beef")
strlist[0].add("Fish")
strlist[1] = {"Apple", "Banana"}
strlist[1].add("Cherry")
print(strlist[0])
print(strlist[1])
print(strlist[2])
print("Array size:", len(strlist))
print(strlist)
The error message says it all: strs[sum-1] is a tuple, not a string. If you show more of your code someone will probably be able to help you. Without that we can only guess.
Sometimes I need a empty char array. You cannot do "np.empty(size)" because error will be reported if you fill in char later. Then I usually do something quite clumsy but it is still one way to do it:
# Suppose you want a size N char array
charlist = [' ']*N # other preset character is fine as well, like 'x'
chararray = np.array(charlist)
# Then you change the content of the array
chararray[somecondition1] = 'a'
chararray[somecondition2] = 'b'
The bad part of this is that your array has default values (if you forget to change them).
def _remove_regex(input_text, regex_pattern):
findregs = re.finditer(regex_pattern, input_text)
for i in findregs:
input_text = re.sub(i.group().strip(), '', input_text)
return input_text
regex_pattern = r"\buntil\b|\bcan\b|\bboat\b"
_remove_regex("row and row and row your boat until you can row no more", regex_pattern)
\w means that it matches word characters, a|b means match either a or b, \b represents a word boundary
If you want to take input from user here is the code
If each string is given in new line:
strs = [input() for i in range(size)]
If the strings are separated by spaces:
strs = list(input().split())
When we need to slice a string at a particular location, we need to know the index from where we want to.
For example, in the string:
>>> s = 'Your ID number is: 41233'
I want to slice the string starting from : and get the number.
Sure I can count at what index : is and then slice, but is that really a good approach?
Of course I can do a s.index(':'). But that would be an extra step, so I came up with something like:
>>> print s[(s.index(':')+2):]
41233
But somehow I don't like the looks of it.
So my question is, given a long string which you want to slice, how do you find the index from where to begin the slicing in the easiest and most readable way? If there is a trick to do it orally, I would love to know that.
Perhaps you could use split():
>>> s = 'Your ID number is: 41233'
>>> print s.split(":")[1].strip()
41233
text, sep, number = 'Your ID number is: 41233'.partition(':')
print number
works too. But it won't fail if the separator is not in the string.
That unpacking works for split too:
text, number = 'Your ID number is: 41233'.split(':',1)
Another approach is 'Your ID number is: 41233'.split(':')[1].strip().
So my question is, given a long string which you want to slice, how do you find the index from where to begin the slicing in the easiest and most readable way?
When "where to begin the slicing" is a specific symbol, you don't; instead you just as Python to split the string up with that symbol as a delimiter, or partition it into the bits before/within/after the symbol, as in the other answers. (split can split the string into several pieces if several delimiters are found; partition will always give three pieces even if the symbol is not there at all.)
If there is a trick to do it orally, I would love to know that.
I really don't think you mean "orally". :)
I wouldn't use slicing at all unless there's some other compelling reason you want to do so. Instead, this sounds like a perfect job for re the regular expression module in the standard library. Here's an example of using it to solve your problem:
import re
compile_obj = re.compile(r'Your ID number is:\s(?P<ID>\d+)')
s = 'Your ID number is: 41233'
match_obj = compile_obj.search(s)
if match_obj:
print match_obj.group('ID')
# 41233
Recently came across partition
string = "Your ID number is: 41233"
string = string.partition(':')
print string[2]