Home > database >  Python reversing individual characters in a string within a list
Python reversing individual characters in a string within a list

Time:03-16

My teachers has set me the task:

Write a sub-routine that

reads in the cities from text file cities.txt (which just contains the names of 7 cities within),

adds them to an array,

reverses the city names without using the inbuilt .reverse option in Python. ie. "london" would become "nodnol"

I have added them to an array however have not been able to reverse each letter then append the reversed string back into the array. right now the output is just the names of the 7 cities within the array whereas I want for each character in each name to be reversed my code is:


cities = []

def read_and_reverse():
  reversedCities = []
  f = open("cities.txt", "r")
  for i in f:
    i = i.strip("\n")
    cities.append(i)
  print(cities)

  

  for city in cities:
    for i in range(0,len(city)):
      index = len(int(i))
      while index:
        index -= 1                       
        reversedCities.append(city[index])
      return ''.join(reversedCities)
  print(reversedCities)
      
read_and_reverse()

CodePudding user response:

Personnaly, I would do something like that:

cities = []

for city in open("cities.txt", "r").readlines():
    cities.append(city[::-1].strip("\n"))
print(cities)

so if there is

abcde1
abcde2
abcde3

in cities.txt, the output would be:

['1edcba', '2edcba', '3edcba']

CodePudding user response:

assuming you have a text file wherein each line contains a city name and you want to produce a list in the same order but with the names of the cities being reversed, I would do it as follows:

def read_and_reverse():
  cities = []
  reversedCities = []
  f = open("cities.txt", "r")
  for i in f:
    i = i.strip("\n")
    cities.append(i)
    reversedCities.append(i[::-1])  #This reverses the string using slicing
  print(cities)
  print(reversedCities)

CodePudding user response:

city_text = """London
Berlin
Paris
Madrid
Milan"""

def reverse_string(s):
    return s[::-1]

cities = []
reverse_cities = []

if False:
    with open("city.txt","r") as f:
        cities = f.read().splitlines()
else:
    cities = city_text.split("\n")
    
for city in cities:
    reverse_cities.append(reverse_string(city))
    
print(reverse_cities)

Output

['nodnoL', 'nilreB', 'siraP', 'dirdaM', 'naliM']

CodePudding user response:

cities = []

def read_and_reverse():
  reversedCities = []
  f = open("cities.txt", "r")
  for i in f:
    i = i.strip("\n")
    cities.append(i)
  print(cities)

  

  for city in cities:
    reversed_city = ""
    for i in range(0,len(city)):
      reversed_city  = city[len(city)-i-1]
    reversedCities.append(reversed_city)
  print(reversedCities)
      
read_and_reverse()
  • Related