This question already has answers here:
How do I reverse a string in Python?
(19 answers)
Return middle part of string
(2 answers)
Swap list / string around a character python
(1 answer)
Python code to swap first and last letters in string
(4 answers)
Write a function swap_halves(s) that takes a string s, and returns a new string in which the two halves of the string have been swapped
(3 answers)
Closed 3 years ago.
In python, how would you swap the first and last parts of a string but leave the middle character in the same place? For example, if I have ABCDE, then the result would be DECAB.
def swap(str1):
return str1[-1]+str1[1:-1]+str1[:1]
print(swap("Hello"))
With this, I am only able to swap the first and last letter of the string. So the result for 'Hello' is 'oellH'.
You can obtain the index of the middle character with the floor division //:
5 //2
# 2
So, you can change your code like this:
def swap(str1):
middle = len(str1) // 2
return str1[middle+1:] + str1[middle] + str1[:middle]
print(swap("ABCDE"))
# DECAB
Note that this only works for strings with an odd number of characters. We could modify the function to also handle strings with even numbers of chars, just swapping both halves in this case:
def swap(str1):
middle = len(str1) // 2
if len(str1) % 2 == 0:
# even length
return str1[middle:] + str1[:middle]
else:
# odd length
return str1[middle+1:] + str1[middle] + str1[:middle]
print(swap("ABCDE"))
# DECAB
print(swap("ABCDEF"))
# DEFABC
Related
This question already has answers here:
Generate random numbers only with specific digits
(3 answers)
Closed 2 years ago.
How would you generate a random number string in Python based on the following conditions.
The string must be between the length of 3 and 7
The string must only contain numbers from 1-7
The string must not have spaces
I tried the following for the string output but I am struggling with the conditionals
letters = string.digits
print ( ''.join(random.choice(letters) for i in range(10)) )
The output I received was:=
9432814671
If you could be kind enough to help me out and guide me I would be grateful to you.
The solution is self-explanatory, and you were close to it:
length = random.randint(3, 7)
"".join(str(random.randint(1, 7)) for _ in range(length))
#'724613'
This question already has answers here:
Python error: "IndexError: string index out of range"
(4 answers)
Closed 3 years ago.
Here is my program I want to find the weather it is a sum string or not based on the following condition
1)the string length must be >3
example:"12358" --- 1+2=3,2+3=5,3+5=8
I tried this program I am getting the index error please help me.Thank you in adavnce.
Given below is my code:
y="12358"
for i in range(len(y)-1):
if y[i]+y[i+1]==y[i+2]:
print "sum stringgg"
The upper bound of the range should be the length of y minus 2 instead to accommodate the comparison with the item of the index plus 2. You should also convert each character in the string to an integer for arithmetic addition and comparison. Finally, you should use the for-else construct to break whenever the former two digits do not add up to the latter digit, and only output 'sum string' if the loop finishes without break:
y = "12358"
digits = list(map(int, y))
for i in range(len(digits) - 2):
if digits[i] + digits[i + 1] != digits[i + 2]:
break
else:
print('sum string')
This question already has answers here:
Count the number of occurrences of a character in a string
(26 answers)
Closed 4 years ago.
#Exercise 7: Counting...1...2...3...
#The purpose of this program is to ask a file from the user, open the file
# and counts the number of comma-separated values in it and report the result to the user
name_file = input("Enter name of file: ")
inf = open(name_file, "r")
count_comma = 0
line = inf.readline()
for char in line:
if "," in char:
count_comma +=1
print (count_comma)
inf.close()
when i run it prints 0. why?
you're probably better off with
count_comma = len(line.split(","))
but you'd have to run timeit to be sure
This question already has answers here:
I can't make the function completely correct
(2 answers)
Closed 8 years ago.
def split_on_separators(original, separators):
""" (str, str) -> list of str
Return a list of non-empty, non-blank strings from the original string
determined by splitting the string on any of the separators.
separators is a string of single-character separators.
>>> split_on_separators("Hooray! Finally, we're done.", "!,")
['Hooray', ' Finally', " we're done."]
"""
# To do: Complete this function's body to meet its specification.
# You are not required to keep the two lines below but you may find
# them helpful. (Hint)
result = [original]
return result
This is how I solved it.
def split_on_separators(original, separators):
""" (str, str) -> list of str
Return a list of non-empty, non-blank strings from the original string
determined by splitting the string on any of the separators.
separators is a string of single-character separators.
>>> split_on_separators("Hooray! Finally, we're done.", "!,")
['Hooray', ' Finally', " we're done."]
"""
result = [original]
for sep in separators:
r = []
for sub in result:
r.extend(sub.split(sep))
result = r
return result
This question already has answers here:
Split a string into 2 in Python
(6 answers)
Closed 3 months ago.
I have this string my_string = '717460881855742062' how can I split it in half? The string is auto-generated so just splitting by the 1 won't work
You can try do this way:
firsthalf, secondhalf = my_string[:len(my_string)//2], my_string[len(my_string)//2:]
Something like this should do the job:
my_string = '717460881855742062'
length = int(len(my_string) / 2)
first_part = my_string[:length]
second_part = my_string[length:]
print(first_part)
print(second_part)
output:
717460881
855742062
You can modify it and make sure you take also handle the situation
where the length%2 is not 0.