How to fix the error "index out of range" - python-3.x

I have to split the string with some "" in the string
I am a beginner in python, plz help me QQ
With the problem that line3 shows "index out of range"
windows
data = input().split(',')
for i in range(len(data)):
for j in range(len(data[i])):
if data[i][j] == '"':
data[i] += "," + data[i + 1]
data.pop(i + 1)
if data[i + 1][j] == '"':
data[i] += "," + data[i + 1]
data.pop(i + 1)
print(data[i])
sample input:
'str10, "str12, str13", str14, "str888,999", str56, ",123,", 5'
sample output:
str10
"str12, str13"
str14
"str888,999"
str56
",123,"
5

Your error occurs if you acces a list/string behind its data. You are removing things and access
for i in range(len(data)):
...
data[i] += "," + data[i + 1]
If i ranges from 0 to len(data)-1 and you access data[i+1] you are outside of your data on your last i!
Do not ever modify something you iterate over, that leads to desaster. Split the string yourself, by iterating it character wise and keep in mind if you are currently inside " ... " or not:
data = 'str10, "str12, str13", str14, "str888,999", str56, ",123,", 5'
inside = False
result = [[]]
for c in data:
if c == ',' and not inside:
result[-1] = ''.join(result[-1]) # add .strip() to get rid of spaces on begin/end
result.append([])
else:
if c == '"':
inside = not inside
result[-1].append(c)
result[-1] = ''.join(result[-1]) # add .strip() to get rid of spaces on begin/end
print(result)
print(*result, sep = "\n")
Output:
['str10', ' "str12, str13"', ' str14', ' "str888,999"', ' str56', ' ",123,"', ' 5']
str10
"str12, str13"
str14
"str888,999"
str56
",123,"
5
Add .strip() to the join-lines to get rid of leading/trailing spaces:
result[-1] = ''.join(result[-1]).strip()

Related

How do I split sentence on 'and'?

I am trying to split my sentence on 'and' but some of the results looks like this
My code
string = 'I am handling it because it is difficult and confusing'
string.split('and')
Results
['I am h', 'ling it because it is difficult ', ' confusing']
I am trying to get this. How do I do it?
['I am handling it because it is difficult ', ' confusing']
Try doing
string.split(" and ")
It will only pick the word.
But if you need spaces, this function/loop will do(tested):
add_spaces(x):
x[0] += ' '
for i in range(1, len(x) - 1):
x[i] = ' ' + x[i]
x[i] += ' '
x[-1] = ' ' + x[-1]

Keep getting else/elif invalid syntax error

Currently I'm writing a code where I want to ask motor values from motor controller using raspberry pi. However my code is throwing InvalidSyntax Error in else and elif statements. I've already read about if and elif statements in python, but I can't figure out mistake by myself. The code is below:
def motor_values():
while 1:
command_1 = '?A '+str(1)+' \r' #Asking first motor current
command_2 = '?A '+str(2)+' \r' #Asking second motor current
counter = 0
#First motor current
if counter = 0:
ser.write(command_1.encode()) #string to bytes
data_1 = ser.readline().decode().strip() #bytes to string
#Checking if data is received and extracting current value
if 'A=' in data_1:
value_1 = int(data_1.split('=')[1])
print("Motor Current(Channel 1): " + str((value_1) + " Ampers")
counter += 1
else:
print("Message is not received")
#Second motor current
elif counter == 1:
ser.write(command_2.encode()) #string to bytes
data_2 = ser.readline().decode().strip() #bytes to string
if 'A=' in data_2:
value_2 = int(data_2.split('=')[1])
print("Motor Current(Channel 2): " + str((value_2) + " Ampers")
counter += 1
else:
print("Message is not received")
else:
counter = 0
A few syntax errors here:
use == in the if clause condition
#First motor current
if counter == 0: #
remove one of the two ( in str((value_2)
print("Motor Current(Channel 1): " + str(value_1) + " Ampers")
print("Motor Current(Channel 2): " + str(value_2) + " Ampers")
you missed closing brace in print function
print("Motor Current(Channel 1): " + str(value_1) + " Ampers")

Simple word scrambler

counter = 0
sentence = 'Hello World'
split = str.split(sentence)
for str in split:
c = split[counter]
scramble = c[4] + c[0] + c[3] + c[1] + c[2]
counter += 1
print (scramble)
The program should rearrange each word in a string into a specific pattern but I cannot figure out how to print the scrambled text onto the same line.
Here you go
counter = 0
sentence = 'Hello World'
split = str.split(sentence)
for str in split:
c = split[counter]
scramble = c[4] + c[0] + c[3] + c[1] + c[2]
counter += 1
print (scramble, end=" ")
The print function accepts an end parameter which defaults to "\n". Setting it to an empty string prevents it from issuing a new line at the end of the line.

Reason for result of output of Python code

why the while loop is executing more times than expected in printing a pascal triangle?
every time the while loop is executed x is incremented by 1 whereas n remains the same
I just started learning python
please help
memo = {0:1}
def fac(n):
if n not in memo:
memo[n] = n*fac(n-1)
return memo[n]
else:
return memo[n]
def pascal(x, space):
while(x <= n):
for j in range(space):
print(" ", end = "")
for i in range(0, x+1):
print ( int(fac(x)/(fac(i)*fac(x-i))), end = " " )
print("\n", end = "")
x += 1
space -= 1
pascal(x, space)
n = eval(input())
space = n
x = 0
pascal(x, space)
You are using two methods to iterate through the numbers in the pascal function, a while loop, and a recursive call. You just need one of them.
Keeping the while loop:
def pascal(x, space):
while(x <= n):
for j in range(space):
print(" ", end = "")
for i in range(0, x+1):
print ( int(fac(x)/(fac(i)*fac(x-i))), end = " " )
print("\n", end = "")
x += 1
space -= 1
Keeping the recursive call, turning the while into an if:
def pascal(x, space):
if(x <= n):
for j in range(space):
print(" ", end = "")
for i in range(0, x+1):
print ( int(fac(x)/(fac(i)*fac(x-i))), end = " " )
print("\n", end = "")
x += 1
space -= 1
pascal(x, space)
Given 3 as input, both versions print the following:
1
1 1
1 2 1
1 3 3 1

Yielding a TypeError: input expected at most 1 arguments, got 4. This error was from the user_input variable associated with strong input

def randomLetters():
numbers = [random.randint(0, 25), random.randint(0, 25)]
alphabet = 'abcdefghijklmnopqrstuvwxyz'
letters = [alphabet[numbers[0]], alphabet[numbers[1]]]
return letters
letters = randomLetters()
print(letters)
print(letters[0])
user_input = input('Enter a word that begins with', "'" + letters[0] + "'", 'and ends with', "'" + letters[1] + "': ")
new_user_input = user_input.lower()
while (new_user_input[0] != letters[0]) and (new_user_input[len(new_user_input) - 1] != letters[1]):
print('Invalid input. Try again.')
new_user_input = input('Enter a word that begins with', "'" + letters[0] + "'", 'and ends with', "'" + letters[1] + "': ")
The user_input variable input is producing a TypeError: input expected at most 1 arguments, got 4
input() only take one arg and you are providing it 4, the , separates arguments, perhaps you meant +:
new_user_input = input('Enter a word that begins with' + "'" + letters[0] + "'" +
'and ends with' + "'" + letters[1] + "': ")
format() helps constructing these strings simpler:
new_user_input = input("Enter a word that begins with '{letters[0]}' and ends with '{letters[1]}': ".format(letters=letters))

Resources