Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
The question is as follows:
"A string exists in CamelCase format. For example: "ThisIsACamelCaseString".
A procedure/function is required that will:
1) prompt for the original entry
2) separate each word of the string
3) store each word in a separate array/list element
4) fill unused array/list elements with a rogue string such as "(Empty)".
After processing the preceding example, the array contents will look like this:
This
Is
A
Camel
Case
String
(Empty)
(Empty)
(Empty)
(Empty)
You may assume that the original string will contain no more than 10 separate words. Write program code in Python for this design."
This is what I tried:
a = input("Enter: ")
lists = list(a)
len = len(a)
alpha = ["Empty"]*10
alpha[0] = lists[0]
for i in range(len):
for j in range(len):
if lists[j + 1].isupper():
break
alpha[i] = alpha[i] + lists[j + 1]
for i in range(10):
print(alpha[i])
How do I find suitable code?
This is one way to do it:
a = 'ThisIsACamelCaseString'
b = [i for i, e in enumerate(a) if e.isupper()] + [len(a)]
c = [a[x: y] for x, y in zip(b, b[1:])]
final = ['(Empty)']*10
for i, case in enumerate(c):
final[i] = case
Use regular expressions to split camel case How to do CamelCase split in python .
Or just iterate over the string in a loop.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
need to convert this list :
a = ["['0221', '02194', '02211']"]
type = list
to this list :
a = ['0221', '02194', '02211']
type = list
If your new to python this code would seem like very complicated, but i will explain whats in this piece of code:
a=["['0221', '02194', '02211']"]
a1=[]
nums_str=""
for i in a:
for j in i:
try:
if j=="," or j=="]":
a1.append(nums_str)
nums_str=""
nums=int(j)
nums_str+=str(nums)
except Exception as e:
pass
else:
a=a1.copy()
print(a)
print(type(a))
Steps:
Used for loop to read the content in list a.
Then again used a for loop to read each character in the string of i.
Then used try to try if i can typecast j into int so that it would only add the numbers to nums_str.
Then appended the nums_str to the list a1 if j if = "," or "]".
Continued the above process on each item in a.
After the for loop gets over, i change a to copy of a1.
You can use astliteral_eval to convert strings to Python data structures. In this case, we want to convert the first element in the list a to a list.
import ast
a = ast.literal_eval(a[0])
print(a)
# ['0221', '02194', '02211']
Note: Python built-in function eval also works but it's considered unsafe on arbitray strings. With eval:
a = eval(a[0]) # same desired output
You can try list comprehension:
a = a[0][2:][:-2].split("', '")
output:
a = ['0221', '02194', '02211']
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
I am extracting values from excel into a list but some of them are blank.
I want to check if the list is empty, and if empty insert 68 empty strings. Is there a way to do that?
a = []
if not a:
#enter 68 empty strings into a. eg: a = ['', '', '',....]
Python lets you multiply a list with a number to repeat it:
a = [''] * 68
If you also have other references to this list, so you actually need to update the same list instead of creating an new one, use extend:
a.extend([''] * 68)
Using the logical or operator, you can avoid conditions to create the list with empty strings, or keep the original list in case it was not empty:
a = a or [''] * 68
If a is empty, then it's falsey so the or will return the second argument.
If a is not empty, it is truthy so the or will return it.
a = []
if not a:
a.extend(["" for _ in range(68)])
Suppose you have a list a, and we want to insert n=68 blank strings at position i
a = [1, 2]
i = 1
n = 68
result = a[:i] + [''] * n + a[i:]
Then of course you can set a = result if you wanted to modify a directly. This is of course overkill, as you don't really want to insert into an existing list, this time, but I thought I'd answer the question asked.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I'm trying to create this kind of output in Python
["k", "kk", "kkk", "kkkk", ...]
["rep", "reprep", "repreprep", ...]
That is a list of n elements, made of the same character (or small group of characters) repeated X times, X being increased by one for each element.
I can't find a way to do this easily, without loops..
Thanks,
Here you have a generator using itertools.count, remember the property of "multiplying" strings in python by a number, where they will be replicated and concatenated nth times, where for example "a"*3 == "aaa" :
import itertools
def genSeq(item):
yield from (item*i for i in itertools.count())
Here you have a live example
repeating_value = "k" #Assign the value which do you want to be repeated
total_times=5 #how many times do you want
expected_list=[repeating_value*i for i in range(1,total_times+1)]
print(expected_list)
character = 'k'
_range = 5
output = [k*x for k in character for x in range(1, _range + 1)]
print(output)
I would multiple my character by a specified number in the range, and then I would simply iterate through the range in a list comprehension. We add 1 to the end of the range in order to get the full range.
Here is your output:
['k', 'kk', 'kkk', 'kkkk', 'kkkkk']
The following is by far the easiest which I have built upon the comment by the user3483203 which eliminates initial empty value.
var = 'rep'
list = [var * i for i in range(1,x,1)]
print(list)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm not a programmer, I'm just starting to learn python 2.
I wanted to know how can I write a code in python 2 to get an input that consists a line of numbers seperated by space from the user and do operations with each number sepeately and print the output of each number, again, as a line of numbers seperated by space?
The below example will loop complete the action you were looking for, just replace the "+5" with the operation you want
userInput = raw_input("Enter Numbers:")#Get user input
seperateNumbers = userInput.split(" ")#Seperate data based off of spaces
numbersAfterOperations = []#Create a lsi to hold the values after operation applied
for i in range(0, len(seperateNumbers)): #loop throgh all values
numbersAfterOperations.append(int(seperateNumbers[i]) + 5) #add new value
printedValue = ""
for i in range(0, len(numbersAfterOperations)):
printedValue += str(numbersAfterOperations[i]) + " "
print printedValue
You will start with a string containing all your numbers, so you will have something like this:
line_of_num = "0 1 2 3 4 5 6 7 8 9"
You will have to split the elements of this string. You can do it using the split method of the string class, using a space as separator. It will return a list of the items with your numbers, but you can't operate them as integers yet.
list_of_num = line_of_num.split(" ")
You can't operate them yet because the elements of your list are strings. Before operating them, you have to cast them into integers. You can do it using list comprehentions.
list_of_int = [int(element) for element in list_of_num]
Then you can operate them using common operations through elements of a list. Finally, when you have the results, you can return them as a string separated by spaces using the join method of the string class using a space as separator. The join method has as input an iterable (list, for example) of strings.
results = " ".join(["1", "2", "3", "4", "5"])
Your resulted string will be something like "1 2 3 4 5".
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Say i have a list formatted something like:a = [a,2,b,3,c,4,d,3]
and i want to write to any file that allows to create superscripts, like:
a^2
b^3
c^4
and so forth. What possible ways can this be done (The indices need to be formatted properly, like actual indices)?
As simple as this:
files=open('write.txt','a')
a = ['a','2','b','3','c','4','d','3']
count=0
while count<len(a):
files.write(a[count]+'^'+a[count+1]+'\n')
count=count+2
Here is a simple way to accomplish that. Replace the print statement with your write and you'll be in good shape.
First prep your list by dividing it into 2 pieces:
a = ['a',2,'b',3,'c',4,'d',3]
first = a[0::2]
second = a[1::2]
Next, loop the first list with enumeration and add the second value:
for i, f in enumerate(first):
super = '%s^%s' % (f, second[i])
print(super) # replace with write function
Output looks like this:
a^2
b^3
c^4
d^3
This should keep it simple!
It's basically just opening a file and then joining successive elements with a ^ and then joining all of these with a line-break. Finally this is written to a file and the file is closed:
with open('filename.txt', 'w') as file:
it = iter(a)
file.write('\n'.join('^'.join([first, str(second)]) for first, second in zip(it, it)))
If you don't want to use any joins and comprehensions you can also use formatting:
with open('filename.txt', 'w') as file:
template = '{}^{}\n' * (len(a) // 2)
formatted = template.format(*a)
file.write(formatted)