how to add commas to a integer string - python

I have a task to create a comma separated list. What I have now works except I'm trying to figure out how to remove the last comma. What I mean is it looks like this with my code 1,2,3, but I need to have it as 1,2,3 is there any way to change what I have now to do this.
new_string = new_string+str(numbers[index])+comma

The easiest way to render a list as a string of comma separated values is str.join. If your list items aren't strings, use str() on each individual item as you join them:
>>> numbers = [1, 2, 3]
>>> ",".join(str(n) for n in numbers)
'1,2,3'

if you want to remove the last char of a string in python you can do this:
new_string = new_string[:-1] or just print(new_string[:-1])
However I'd recommend you check to see if it's the last element and not add the comma that time:
new_string = ''
my_list = [1,2,3,4]
for i, item in enumerate(my_list):
if i + 1 == len(my_list):
new_string += f'{item}'
else:
new_string += f'{item},'

try this:
#your ,ed output
mystr = "1,2,3,4,"
#removes the last item of the string
mylist = list(mystr)
mystr = ""
mylist[len(mylist)-1] = "";
for x in mylist:
mystr += x
#prints output(1,2,3,4)
print(mystr)
the first part sets 'myvar' to "1,2,3,4,"
then it turns 'myvar' into a list and removes the last element
replace 'myvar' width your output

Related

Replace sequence of the same letter with single one

I am trying to replace the number of letters with a single one, but seems to be either hard either I am totally block how this should be done
So example of input:
aaaabbcddefff
The output should be abcdef
Here is what I was able to do, but when I went to the last piece of the string I can't get it done. Tried different variants, but I am stucked. Can someone help me finish this code?
text = "aaaabbcddefff"
new_string = ""
count = 0
while text:
for i in range(len(text)):
l = text[i]
for n in range(len(text)):
if text[n] == l:
count += 1
continue
new_string += l
text = text.replace(l, "", count)
break
count = 0
break
Using regex
re.sub(r"(.)(?=\1+)", "", text)
>>> import re
>>> text = "aaaabbcddefff"
>>> re.sub(r"(.)(?=\1+)", "", text)
abcdeaf
Side note: You should consider building your string up in a list and then joining the list, because it is expensive to append to a string, since strings are immutable.
One way to do this is to check if every letter you look at is equal to the previous letter, and only append it to the new string if it is not equal:
def remove_repeated_letters(s):
if not s: return ""
ret = [s[0]]
for index, char in enumerate(s[1:], 1):
if s[index-1] != char:
ret.append(char)
return "".join(ret)
Then, remove_repeated_letters("aaaabbcddefff") gives 'abcdef'.
remove_repeated_letters("aaaabbcddefffaaa") gives 'abcdefa'.
Alternatively, use itertools.groupby, which groups consecutive equal elements together, and join the keys of that operation
import itertools
def remove_repeated_letters(s):
return "".join(key for key, group in itertools.groupby(s))

Appending a char to an empty list

I am very new to programming, so sorry for a basic question. I am trying to write a function that will take a string in which words are divided by ',' and return a list of these words (the Split method). My code is:
def str_to_list(my_shop_str):
my_shop_list = ['']
word_in_list = 0
for letter in my_shop_str:
if letter != ',':
my_shop_list[word_in_list] += letter
else:
word_in_list += 1
my_shop_list + ['']
return my_shop_list
print(str_to_list("Milk,Cottage,Tomatoes")) should look like [Milk, Cottage, Tomatoes]
but I am keep getting IndexError: list index out of range.
I read some answers here and couldn't find something to work.
Can anyone explain what is wrong.
list has the method append so a solution will be something like this:
def str_to_list(my_shop_str):
my_shop_list = ['']
word_in_list = 0
for letter in my_shop_str:
if letter != ',':
my_shop_list[word_in_list] += letter
else:
word_in_list += 1
my_shop_list.append('')
return my_shop_list
PS: Do not forgot about empty spaces between words in string like "aaa, bbb, ccc" will be ['aaa', ' bbb', ' ccc'] with spaces.
def sp(s):
l =[]
while True:
comma = s.find(',')
if comma == -1:
l.append(s)
break
l.append(s[:comma])
s = s[comma+1:]
print(l)
this is a simplified version hope it helps.
Simplest Way:
We can use an inbuilt split function.
def Convert(string):
# split the string whenever "," occurs
# store the splitted parts in a list
li = list(string.split(","))
return li
# Driver code
str1 = "Hello,World"
print(Convert(str1))
Output:
["Hello", "World"]

Python, Output all words from a list found in a string in order of apperance

The function takes a list of words that I want to return, if they appear in the string, as a string separated by " ". However, right now they will be returned in the order of apperance in my list passed to the function. How can I modify my function so they are returned in the order of apperance in the string ?
Only similar post I found was this one which return the first word and its in python 2.x :
Grab the first word in a list that is found in a string. ( Python )
def ifExiste(set):
count_tweet_adding = 0
tempvalue = []
value = ""
x=0
old_count = count_tweet_adding
for element in set:
if (word_tweet.find(element) >= 0):
tempvalue.append(element.strip())
count_tweet_adding +=1
value = tempvalue[0]
if (old_count == count_tweet_adding):
value = "NaN"
while x < len(tempvalue)-1:
x += 1
value = value + " " + tempvalue[x]
return value
EDIT :
Here is how I did it:
I added a loop to filter words that are in both the string and my list of words and then used this filtered list with the 'brute force' method to check my string letter by letter. I also added a replace lign to take the word I picked up out of the string so I can capture it twice if it appears twice in my string.
def ifExiste(text, input_list):
count_tweet_adding = 0
tempvalue = []
value = ""
old_count = count_tweet_adding
filtered_input_list = []
for word in input_list:
if word in text:
filtered_input_list.append(word)
for length in range(len(text)):
for word in filtered_input_list:
if word in text[:length+1]:
tempvalue.append(word)
text = text[:length+1].replace(word,'')+text[length+2:]
count_tweet_adding +=1
tempvalue = map(str.strip, tempvalue)
value = " ".join(tempvalue)
if (old_count == count_tweet_adding):
value = "NaN"
return value
Here's a quick and dirty (bruteforce) solution.
Assume that you have a string of the following sort to compare against, since you mentioned the separator (or delimiter) is "".
>>> s = "herearesomewordsinastringinsomeorder"
Now assume you have a list l, the words from which you want to compare against s and document.
>>> l = ['string', 'the', 'in', 'appear', 'words', 'these', 'do']
You could then initialize a new list, newlist, to document the words in l in the same order they appear in s.
>>> newlist = []
Then you could write a for-each-in loop of the sort:
>>> for length in range(len(s)):
... for word in l:
... if word in s[:length+1] and word not in newlist:
... newlist.append(word)
Which, on evaluation, would give you:
>>> newlist
['words', 'in', 'string']
in the order they appeared in s.
You may be able do this with an expression!
def fn(s, input_list):
return list(x for x in s.split() if x in input_list)
This works by first making your string s into a list, then iterating over it, finding all the members that are in input_list
>>> fn("one two three", ["three", "two", "missing"])
['two', 'three']
This should be perfectly reasonable for small strings
If you want to create a new string, you can use " ".join()"
>>> " ".join(fn("one two three", ["three", "two", "missing"]))
'two three
If you always want to return a new string, you can directly return the joined value instead of creating a new list.
def fn(s, input_list):
return " ".join(x for x in s.split() if x in input_list)

How to replace characters in a string in python

How to replace characters in a string which we know the exact indexes in python?
Ex : name = "ABCDEFGH"
I need to change all odd index positions characters into '$' character.
name = "A$C$E$G$"
(Considered indexes bigin from 0 )
Also '$'.join(s[::2])
Just takes even letters, casts them to a list of chars and then interleaves $
''.join(['$' if i in idx else s[i] for i in range(len(s))])
works for any index array idx
You can use enumerate to loop over the string and get the indices in each iteration then based your logic you can keep the proper elements :
>>> ''.join([j if i%2==0 else '$' for i,j in enumerate(name)])
'A$C$E$G$'
name = "ABCDEFGH"
nameL = list(name)
for i in range(len(nameL)):
if i%2==1:
nameL[i] = '$'
name = ''.join(nameL)
print(name)
You can reference string elements by index and form a new string. Something like this should work:
startingstring = 'mylittlestring'
nstr = ''
for i in range(0,len(startingstring)):
if i % 2 == 0:
nstr += startingstring[i]
else:
nstr += '$'
Then do with nstr as you like.

python - ordinal value - list indices must be integers not str

what i want to do is take a string and for each character make the ordinal value 1 more from the value it has.
myinput=input("Message : ")
mylist =list(myinput) #convert to list in order to take each character
for character in mylist:
mylist[character]+=ord(mylist[character])+1
print(character)
The problem is with the "ord(mylist[character])+1"
Thank you!
Probably you are looking for the next:
>>> m = raw_input('Message:')
Message:asdf
>>> ''.join(chr(ord(c) + 1) for c in m)
'bteg'
Notes:
use raw_input when you need to get string input from a user;
ord convert character to integer, chr - vise versa;
... for c in m syntax is a generator expression. It is also used for list comprehension.
Three problems here. First, you're mixing up list indices and list elements. Second, you didn't convert back to a character (I'm assuming you want characters, not numbers). Third, you're adding to the existing value.
One way:
for i range(len(mylist)):
mylist[i] = chr(ord(mylist[i])+1)
Another way:
for i, character in enumerate(mylist):
mylist[i] = chr(ord(character)+1)
Instead of
for character in mylist:
mylist[character]+=ord(mylist[character])+1
(where character is a list index and therefore invalid), you probably want:
mylist = [ord(character) + 1 for character in mylist]
Or a Counter.
You can do like this
def ordsum(astring, tablesize):
sum = 0
for num in range(len(astring)):
sum = sum + ord(astring[num])
return sum
myinput = input() # use raw_input() in Python 2
myinput = map(lambda ch: chr(ord(ch) + 1), myinput)
# or list comp.
myinput = [chr(ord(ch) + 1) for ch in myinput]
You can iterate directly over a string, you do not have to make it a list first. If your end goal is to have a new string, you can do this:
myinput=input("Message : ")
result = []
for character in myinput:
result.append( chr( ord( character ) + 1 )
mynewstring = ' '.join(result)

Categories

Resources