Cannot remove the right end space of the output string - python-3.x

import random
string = ''
keys = ['car', 'banana', 'groof', 'jump', 'king', 'alley']
temp = random.randint(2,3)
for i in range(temp):
string = string + random.choice(keys) + ' '
string.strip()
print(string)
I'm just learning programming
Even if you use the strip function,
the space on the right end does not disappear.
What did I do wrong?

The strip function returns the modified string but it does't modify the orignal string it only returns it which need to be stored in another string
import random
string = ''
keys = ['car', 'banana', 'groof', 'jump', 'king', 'alley']
temp = random.randint(2,3)
for i in range(temp):
string = string + random.choice(keys) + ' '
str=string.strip()
print(str)

I suggest using a list comprehension along with string join() here:
keys = ["car", "banana", "groof", "jump", "king", "alley"]
temp = random.randint(2,3)
x = ' '.join([random.choice(keys) for i in range(temp)])
print(x)

Related

Create a list of strings with one/multiple character replacement

How to create a whole list of string from one string where each string in the list containing exactly one character replacement? The string itself is consisted of only four characters (say: A, B, C, and D), so that the whole list of a string of length n would contain 3n+1 strings with exactly one character replacement.
Example:
inputstr = 'ABCD'
output = ['ABCD', 'BBCD', 'CBCD', 'DBCD', 'AACD', 'ACCD', 'ADCD', 'ABAD', 'ABBD', 'ABDD', 'ABCA', 'ABCB', 'ABCC']
I write the following python code:
strin = 'ABCD'
strout = set()
tempstr1 = ''
tempstr2 = ''
tempstr3 = ''
tempstr4 = ''
for base in range(len(strin)):
if strin[base] == 'A': #this block will be repeated for char B, C and D
tempstr1 = strin.replace(strin[base], 'A')
strout.add(tempstr1)
tempstr1 = ''
tempstr2 = strin.replace(strin[base], 'B')
strout.add(tempstr2)
tempstr2 = ''
tempstr3 = strin.replace(strin[base], 'C')
strout.add(tempseq3)
tempstr3 = ''
tempstr4 = strin.replace(strin[base], 'D')
strout.add(tempseq4)
tempstr4 = ''
return strout
and it works well as long as there is no repeated character (such as 'ABCD'). However, when the input string contains repeated character (such as 'AACD'), it will return less than 3n+1 string. I tried with 'AACD' string and it returns only 10 instead of 13 strings.
Anyone can help?
change
strout = set() ===> strout = list()
I found it. I used a slicing method to create a list of total combination of strings with one replacement.
for i in range(len(seq)):
seqxlist.append(seq[:i] + 'x' + seq[i+1:])
and after that I filter out all the x-replaced strings which are longer than the original string length:
seqxlist = [x for x in seqxlist if (len(x) == len(seq))]
Then, I changed x into any of the substitution characters:
for m in seqxlist:
tempseq1 = m.replace('x', 'A')
outseq.append(tempseq1)
tempseq2 = m.replace('x', 'B')
outseq.append(tempseq2)
tempseq3 = m.replace('x', 'C')
outseq.append(tempseq3)
tempseq4 = m.replace('x', 'D')
outseq.append(tempseq4)
This will create all the possible combinations of string replacement, but still contains duplicates. To remove duplicates, I use set() to the outseq list.

How to make a string only have letters in python

from random import randint
Text = ""
Text2 = ""
Text3 = ""
Final = ""
Final2 = ""
inp = input(str("What's your name?"))
Greet = randint(1,3)
File = open("File2.txt","w")
File.write(inp+",")
File.write("YoYoYo,")
File.write("Hi,")
File.write("Hey,")
File.close()
File = open("File2.txt","r")
for line in File:
Text = line.split(",")
Text2 = (Text[Greet])
Text3 = Text[0]
Final = (Text2,Text3)
Final = str(Final)
print(Final)
File.close()
Because I am setting the Variable "Final" using parts from a list this is the result:
What's your name?Mark
('YoYoYo', 'Mark')
I want it to print it normally without the brackets, comma and '' like:
YoYoYo Mark
Is there a way I can easily remove the brackets, comma and ''?
Problem sorted ;p Thanks <3
(Text2,Text3) is a tuple, tuples are printed that way, if you want a string that is the composition of other strings, you should concatenate the other strings using the + operator:
Final = Text2 + ' ' + Text3
print(Final) # => YoYoYo Mark
Pass them to the print function directly:
You are assigning a tuple to the variable Final and then printing it which prints with brackets as it is a tuple. You don't need to bother with any of that as you can just pass both Text2 and Text3 directly into the print() function:
print(Text2, Text3)
and they will print with a space between them:
YoYoYo Mark

Matlab String Conversion to Array

I got a string array of the format
sLine =
{
[1,1] = 13-Jul-16,10.46,100.63,15.7,54.4,55656465
[1,2] = 12-Jul-16,10.47,100.64,15.7,54.4,55656465
[1,3] = 11-Jul-16,10.48,100.65,15.7,54.4,55656465
[1,4] = 10-Jul-16,10.49,100.66,15.7,54.4,55656465
}
In which each element is a string ("13-Jul-16,10.46,100.63,15.7,54.4,55656465" is a string).
I need to convert this to 6 vectors, something like
[a b c d e f] = ...
such a way, for example, for the 1st column, it would be
a = [13-Jul-16;12-Jul-16;11-Jul-16;10-Jul-16]
I tried to use cell2mat function, but for some reason it does not separate the fields into matrix elements, but it concatenates the whole string into something like
cell2mat(sLine)
ans =
13-Jul-16,10.46,100.63,15.7,54.4,5565646512-Jul-16,10.47,100.64,15.7,54.4,5565646511-Jul-16,10.48,100.65,15.7,54.4,5565646510-Jul-16,10.49,100.66,15.7,54.4,55656465
So, how can I solve this?
Update
I got the sLine matrix following the steps
pFile = urlread('http://www.google.com/finance/historical?q=BVMF:PETR4&num=365&output=csv');
sLine = strsplit(pFile,'\n');
sLine(:,1)=[];
Update
Thanks to #Suever I could get now the column dates. So the updated last version of the code is
pFile = urlread('http://www.google.com/finance/historical?q=BVMF:PETR4&num=365&output=csv');
pFile=strtrim(pFile);
sLine = strsplit(pFile,'\n');
sLine(:,1)=[];
split_values = regexp(sLine, ',', 'split');
values = cat(1, split_values{:});
values(:,1)
Your data is all strings, therefore you will need to do some string manipulation rather than using cell2mat.
You will want to split each element at the ,characters and then concatenate the result together.
sLine = {'13-Jul-16,10.46,100.63,15.7,54.4,55656465',
'12-Jul-16,10.47,100.64,15.7,54.4,55656465',
'11-Jul-16,10.48,100.65,15.7,54.4,55656465',
'10-Jul-16,10.49,100.66,15.7,54.4,55656465'};
split_values = cellfun(#(x)strsplit(x, ','), sLine, 'uniformoutput', 0);
values = cat(1, split_values{:});
values(:,1)
% {
% [1,1] = 13-Jul-16
% [2,1] = 12-Jul-16
% [3,1] = 11-Jul-16
% [4,1] = 10-Jul-16
% }
If you want it to be more concise, we can just use regexp to split it up instead of strsplit since it can accept a cell array as input.
split_values = regexp(sLine, ',', 'split');
values = cat(1, split_values{:});
Update
The issue with the code that you've posted is that there is a trailing newline in the input and when you split on newlines the last element of your sLine cell array is empty causing your issues. You'll want to use strtrim on pFile before creating the cell array to remove trailing newlines.
sLine = strsplit(strtrim(pFile), '\n');
sLine(:,1) = [];

Split a string and store in an array in lua

I need to split a string and store it in an array. here i used string.gmatch method, and its splitting the characters exactly, but my problem is how to store in an array ? here is my script.
my sample string format : touchedSpriteName = Sprite,10,rose
objProp = {}
for key, value in string.gmatch(touchedSpriteName,"%w+") do
objProp[key] = value
print ( objProp[2] )
end
if i print(objProp) its giving exact values.
Your expression returns only one value. Your words will end up in keys, and values will remain empty. You should rewrite the loop to iterate over one item, like this:
objProp = { }
touchedSpriteName = "touchedSpriteName = Sprite,10,rose"
index = 1
for value in string.gmatch(touchedSpriteName, "%w+") do
objProp[index] = value
index = index + 1
end
print(objProp[2])
This prints Sprite (link to demo on ideone).
Here's a nice function that explodes a string into an array. (Arguments are divider and string)
-- Source: http://lua-users.org/wiki/MakingLuaLikePhp
-- Credit: http://richard.warburton.it/
function explode(div,str)
if (div=='') then return false end
local pos,arr = 0,{}
for st,sp in function() return string.find(str,div,pos,true) end do
table.insert(arr,string.sub(str,pos,st-1))
pos = sp + 1
end
table.insert(arr,string.sub(str,pos))
return arr
end
Here is a function that i made:
function split(str, character)
result = {}
index = 1
for s in string.gmatch(str, "[^"..character.."]+") do
result[index] = s
index = index + 1
end
return result
end
And you can call it :
split("dog,cat,rat", ",")
Reworked code of Ricardo:
local function split (string, separator)
local tabl = {}
for str in string.gmatch(string, "[^"..separator.."]+") do
table.insert (tabl, str)
end
return tabl
end
print (unpack(split ("1234#5678#9012", "#")))
-- returns 1234 5678 9012

Split string and replace dot char in Lua

I have a string stored in sqlite database and I've assigned it to a var, e.g. string
string = "First line and string. This should be another string in a new line"
I want to split this string into two separated strings, the dot (.) must be replace with (\n) new line char
At the moment I'm stuck and any help would be great!!
for row in db:nrows("SELECT * FROM contents WHERE section='accounts'") do
tabledata[int] = string.gsub(row.contentName, "%.", "\n")
int = int+1
end
I tried the other questions posted here in stachoverflow but with zero luck
What about this solution:`
s = "First line and string. This should be another string in a new line"
a,b=s:match"([^.]*).(.*)"
print(a)
print(b)
Are you looking to actually split the string into two different string objects? If so maybe this can help. It's a function I wrote to add some additional functionality to the standard string library. You can use it as-is or rename it to what ever you like.
--[[
string.split (s, p)
====================================================================
Splits the string [s] into substrings wherever pattern [p] occurs.
Returns: a table of substrings or, if no match is made [nil].
--]]
string.split = function(s, p)
local temp = {}
local index = 0
local last_index = string.len(s)
while true do
local i, e = string.find(s, p, index)
if i and e then
local next_index = e + 1
local word_bound = i - 1
table.insert(temp, string.sub(s, index, word_bound))
index = next_index
else
if index > 0 and index <= last_index then
table.insert(temp, string.sub(s, index, last_index))
elseif index == 0 then
temp = nil
end
break
end
end
return temp
end
Using it is very simple, it returns a tables of strings.
Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio
> s = "First line and string. This should be another string in a new line"
> t = string.split(s, "%.")
> print(table.concat(t, "\n"))
First line and string
This should be another string in a new line
> print(table.maxn(t))
2

Resources